Reputation: 39628
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
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