This is bound to be a duplicate question but I can't find any others. I'm trying to get a list of photos that have complaints. I can't simply get complaints and deal with the related photos - I need a queryset of photos.
This should work but doesn't seem right:
Photo.objects.filter(complaint__id__gte=0)
This doesn't seem like the most efficient way:
Photo.objects.annotate(Count('complaint')).exclude(complaint__count=0)
Is there a better way?
With the Django QuerySet class, you can apply filters that return QuerySets defined by your filters. The filter() method returns all objects that match the keyword arguments given to the method.
Definition and Usage. The exact lookup is used to get records with a specified value. The exact lookup is case sensitive. For a case insensitive search, use the iexact lookup.
The filter() method is used to filter you search, and allows you to return only the rows that matches the search term.
Using Django ORM, we can instantly get any data from the database anywhere in our code. This is very convenient. But there is a problem if we are fetching a foreign key or many-to-many fields many times in a row.
how about ...
Photo.objects.filter(complaint__isnull=False)
from https://docs.djangoproject.com/en/dev/topics/db/queries/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With