getting elements with a queryset based on a left join in django

I have two models:

class A(models.Model):
    field1 = models.CharField(max_length=100)
    field2 = models.CharField(max_length=100)

class B(models.Model):
    a_field = models.ForeignKey(null=True,blank=True,related_name='a',on_delete=models.SET_NULL)
    field2 = models.CharField(max_length=100)

I want to get all of elements of model A which are not related to B.
Here is the query I wrote but it doesn’t work:

B.objects.select_related("a_field").filter(a_field__isnull=True)

How can I solve this problem?

>Solution :

I want to get all of elements of model A which are not related to B.

You can query with:

A.objects.filter(a=None)

The a origiates from the related_name=… value [Django-doc] for the ForeignKey, but it makes no sense to name that 'a', since it is the relation in reverse, so from A to B, usually it makes more sense to name that 'bs‘, so:

class B(models.Model):
    a_field = models.ForeignKey(
        A,
        null=True,
        blank=True,
        related_name='bs',
        on_delete=models.SET_NULL
    )
    # …

and thus query with:

A.objects.filter(bs=None)

Leave a Reply