Search code examples
djangofiltermodels

Django using foreignKey to retrieve one attribute in a query


In my django code I have these two objects :

class A(models.Model):
  ...

class B(models.Model)
  flag = models.BooleanField(default=False)
  type = models.ForeignKey(A)
  ...

I'd like to do something like :

A.objects.filter(...)

in my filter I'd like to only have the A whose has at least 1 B with the flag = True linked. Is it possible to do this directly using the filter ? rather than having a loop and then :

a.b_set.filter(flag__exact=1).count() > 0

Solution

  • Specifying b__flag=... will give you what you want.

    A.objects.filter(b__flat=True)
    

    Above could yield duplicated A objects. Prevent that, use QuerySet.distinct:

    A.objects.filter(b__flat=True).distinct()