Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django queryset exclude empty foreign key set

Tags:

django

I have the following models where B has a many-to-one relationship with A:

class A(model.Model):

    name = models.IntegerField()

class B(models.Model

    a = models.ForeignKey(A, db_column='a_id')

When I use a queryset on A, is there a way to exclude the rows in A that have no rows in B?

like image 949
Hank Avatar asked Aug 20 '15 18:08

Hank


3 Answers

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.

like image 108
Alasdair Avatar answered Oct 18 '22 20:10

Alasdair


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)
like image 1
Incognos Avatar answered Oct 18 '22 21:10

Incognos


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.

like image 1
Nick Cuevas Avatar answered Oct 18 '22 20:10

Nick Cuevas