[Fixed]-Django queryset exclude empty foreign key set

32👍

Use isnull :

A.objects.filter(b__isnull=False).distinct()

Using distinct() prevents duplicate entries, otherwise each a appears once for every b which is linked to it.

1👍

no_rows_in_b = B.objects.all().select_related('a')

will get you all the B’s with A’s

Then you can cycle through them and output the A’s

If you want non-repeats:

no_rows_in_b = B.objects.all().distinct('a').select_related('a')

Then:

for rec in no_rows_in_b:
    print(rec.a)

1👍

Notice that if you want to be more explicit, you could do something like this:

A.objects.exclude(b__isnull=True).distinct()

using exclude instead of filter and using the True boolean arg.

Leave a comment