简体   繁体   中英

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

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

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:

{% 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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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