简体   繁体   English

Django 按外键过滤对象

[英]Django filter objects by Foreign Key

I have troubles with filtering objects.我在过滤对象时遇到了麻烦。 The objects are displaying in all lists but I have set Foreign key for specific list.对象显示在所有列表中,但我为特定列表设置了外键。 Is there any solutions?有什么解决办法吗?

models.py模型.py

class Lists(models.Model):
    title = models.CharField(max_length=200)  

class ListsItem(models.Model):
    date = models.DateTimeField(default=datetime.now,blank=True)
    title = models.CharField(max_length=200)   
    main_list=models.ForeignKey(Lists, on_delete=models.SET_NULL, null=True)

views.py视图.py

lists = Lists.objects.order_by('date')
listitems = ListsItem.objects.filter(main_list__in=lists).order_by('date')

template模板

{% if lists %}
{% for list in lists %}

{{list.title}}


{% if listitems %}
{% for listitem in listitems %}

{{listitem.title_item}}


{% endfor %}   
{% endif %}


{% endfor %}  
{% endif %}

Instead of 2 seperate lists you could fetch your objects inside the template for each Lists -object:您可以在模板中为每个Lists对象获取对象,而不是 2 个单独的列表:

{% for list in lists %}
...
{% for item in list.listsitem_set.all %}

... do something with related items

{% endfor %}
...

Furthermore to improve the queries you can work with prefetch_related , like:此外,为了改进您可以使用prefetch_related的查询,例如:

lists = Lists.objects.order_by('date').prefetch_related('listsitem_set')

And if you don't want to individually set order_by , just add ordering to the models Meta -class.如果您不想单独设置order_by ,只需将ordering添加到模型Meta -class。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM