Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading