简体   繁体   中英

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)

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))
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM