Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter Django objects where related object exists

Tags:

django

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?

like image 481
Jake Avatar asked Dec 11 '12 21:12

Jake


People also ask

Can I filter a QuerySet Django?

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.

What is __ exact in Django?

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.

What is the purpose of filter () method in Django?

The filter() method is used to filter you search, and allows you to return only the rows that matches the search term.

Is Django ORM efficient?

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.


1 Answers

how about ...

Photo.objects.filter(complaint__isnull=False)

from https://docs.djangoproject.com/en/dev/topics/db/queries/

like image 200
jcfollower Avatar answered Sep 30 '22 16:09

jcfollower