Django reverse lookup foreign keys with multiple conditions

I am trying to do a reverse lookup in Django with multiple conditions, hopefully, my question does not duplicate with other questions. Let me explain:

I have two models: Model A:

class A(models.Model):
    title = models.CharField(max_length=200)
    ... other fields

Model B:

class B(models.Model):
    a = models.ForeignKey(A)
    label = models.CharField(max_length=200)
    value = models.CharField(max_length=200)
    ... other fields

How can I get A that: 1) has a B with label = name, value=John 2) and, has a B with label =age, value =20

I tried the following, it does not work:

A.objects.filter(b__label="name", b__value="John", b__label="age", b__value=20)

1 answer

  • answered 2018-10-09 16:30 neverwalkaloner

    You can use Q object:

    from django.db.models import Q
    
    A.objects.filter(
        (Q(b__label="name") & Q(b__value="John")) | (Q(b__label="age") & Q(b__value=20))
    )