【问题标题】:what is the right way to query a manytomany field in django在 django 中查询多对多字段的正确方法是什么
【发布时间】:2012-12-06 07:34:04
【问题描述】:

所以我有一个模型,

class Category(SmartModel):
    item=models.ManyToManyField(Item)
    title=models.CharField(max_length=64,help_text="Title of category e.g BreakFast")
    description=models.CharField(max_length=64,help_text="Describe the category e.g the items included in the category")
    #show_description=check box if description should be displayed
    #active=check box if category is still avialable
    display_order=models.IntegerField(default=0)
    def __unicode__(self):
        return "%s %s %s %s " % (self.item,self.title, self.description, self.display_order)

如你所见,它有一个多对多字段

item=models.ManyToManyField(Item) 

我想返回模板中的所有项目,这是我的views.py

def menu(request):
    categorys= Category.objects.all()
    items= categorys.all().prefetch_related('item')
    context={
        'items':items,
        'categorys':categorys
    }
    return render_to_response('menu.html',context,context_instance=RequestContext(request))

这是在模板中的做法,

    <ul>
{% for item in items %}
 <li>{{ item.item }}

 </li>
</ul>
{% endfor %}

毕竟,这就是它在我的网页中返回的内容,

<django.db.models.fields.related.ManyRelatedManager object at 0xa298b0c>

我做错了什么,我真的环顾四周但都是徒劳的,希望你能帮助我并提前感谢你

【问题讨论】:

    标签: django django-models django-orm


    【解决方案1】:

    没错,您有一个多对多经理。你需要实际查询一些东西......比如all()

    {% for item in items %}
       {% for i in item.item.all %}
            {{ i }}
       {% endfor %}
    {% endfor %}
    

    根据您的变量命名,我认为您将prefetch_related 的结果混淆为一堆items。它实际上是返回一个 Category 对象的 QuerySet。

    因此将它们称为类别会更直观。

    {% for category in categories %}
       {% for item in category.item.all %} 
           {{ item }} {# ...etc #}
    

    【讨论】:

    • 我确实对变量进行了研究,感谢您指出这一点
    【解决方案2】:

    尝试使用:

    categorys= Category.objects.prefetch_related('item').all()
    

    然后在模板中:

    {% for category in categorys %}
        {% for item in category.item.all %}
            {{ item }}
        {% endfor %}
    {% endfor %}
    

    【讨论】:

    • 是的,你是对的,我忘记了“.item.all” - Yuri 向你展示了确切的方式:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-05
    • 2011-04-07
    • 2011-03-25
    相关资源
    最近更新 更多