Django - 使用 Q 跨越空关系的查询集
考虑模型:
#Models
class A(models.Model):
fieldOfA = models.CharField(max_length = 4)
class B(models.Model):
fieldOfB = models.CharField(max_length = 4)
class C(models.Model):
classA = models.ForeignKey(A, blank=True, null=True)
classB = models.ForeignKey(B, blank=True, null=True)
当我创建 C 的对象时,我确保对象具有 classA 或 classB 关系。
我正在寻找一个查询集,它可以为我获取特定 fieldOfA 或特定 fieldOfB 值的 C 对象。
我尝试了这个,但它失败了(返回[],尽管有有效的结果)。
#Views - assume double underscore in the query
from django.db.models import Q
my_query = C.objects.filter(Q(classA _ _isnull = False, classA _ _fieldOfA = 'foo') | Q(classB _ _isnull = False, classB _ _fieldOfB = 'foo'))
我看到的问题是“|” 这就是应用的。 A 类和 B 类的两个不同查询集工作正常。 有什么方法可以应用单个查询集来完成这项工作吗? 或者更糟糕的是,一种合并各个查询集的方法。
Consider the models:
#Models
class A(models.Model):
fieldOfA = models.CharField(max_length = 4)
class B(models.Model):
fieldOfB = models.CharField(max_length = 4)
class C(models.Model):
classA = models.ForeignKey(A, blank=True, null=True)
classB = models.ForeignKey(B, blank=True, null=True)
When I create objects of C, I ensure that an object has EITHER a classA or classB relationship.
I am looking for a single queryset, which gets me objects of C for specific fieldOfA or specific fieldOfB values.
I tried this, but it fails (returns [], despite there being valid results).
#Views - assume double underscore in the query
from django.db.models import Q
my_query = C.objects.filter(Q(classA _ _isnull = False, classA _ _fieldOfA = 'foo') | Q(classB _ _isnull = False, classB _ _fieldOfB = 'foo'))
The problem I see is the '|' that is the applied. Two different querysets for classA and classB work fine. Any way I could apply a single queryset to make this work? Or worse, a way to merge the individual querysets.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您可以确定 C 具有 A 或 B,但不能同时具有两者,则您的
isnull
约束是多余的。 如果运行以下命令会发生什么?如果仍然不起作用,请运行
manage.py shell
并在运行上述查询后(确保settings.DEBUG
为True
,检查上面生成的 SQL 与What do you see?
If you can be sure that a C either has an A or a B but never both, your
isnull
constraints are redundant. What happens if you run the following?If that still doesn't work, run
manage.py shell
and after running the above query (ensuring thatsettings.DEBUG
isTrue
, check the generated SQL for the above withWhat do you see?
实际上,您可以以相同的方式组合
QuerySet
。 就像这样:Actually, you can combine
QuerySet
s in the same way. Like so: