0

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 %}

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.