Kimvais
Kimvais

Reputation: 39628

What is the optimal way to find out if ManyRelatedManager is an empty QuerySet in django

I have 2 models, Bacon and Eggs that both have ForeignKey to Spam model.

I need to find out the Bacon's that are not related to Eggs, currently I'm doint it in the following way:

objs = Bacon.objects.select_related.filter(somefilter=value)

for obj in objs:
    if obj.spam.eggsspam.count():
        continue

    do_something()

I'm sure there must be a more optimal way?

Upvotes: 1

Views: 857

Answers (2)

Elliott
Elliott

Reputation: 1376

You want annotations. The code will look similar to this:

Bacon.objects.annotate(num_eggs=Count('spam__egg_set')).filter(num_eggs__eq=0)

Upvotes: 2

Chris Pratt
Chris Pratt

Reputation: 239460

Try:

Bacon.objects.filter([m2m_field_name]__isnull=True)

Upvotes: 3

Related Questions