How to get a list of queryset and make custom filter in Django
I have some codes like this:
cats = Category.objects.filter(is_featured=True)
for cat in cats:
entries = Entry.objects.filter(score>=10, category=cat).order_by("-pub_date")[:10]
But, the results just show the last item of cats and also have problems with where ">=" in filter. Help me sol开发者_开发知识库ve these problems. Thanks so much!
You may want to start by reading the django docs on this subject. However, just to get you started, the filter()
method is just like any other method, in that it only takes arguments and keyword args, not expressions. So, you can't say foo <= bar
, just foo=bar
. Django gets around this limitation by allowing keyword names to indicate the relationship to the value you pass in. In your case, you would want to use:
Entry.objects.filter(score__gte=10)
The __gte
appended to the field name indicates the comparison to be performed (score >= 10
).
Your not appending to entries
on each iteration of the for loop, therefore you only get the results of the last category. Try this:
entries = Entry.objects.filter(score__gte=10, category__is_featured=True).order_by("-pub_date")[:10]
精彩评论