过滤来自另一个模型的任何引用 [英] Filtering by any reference from another model
本文介绍了过滤来自另一个模型的任何引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
class A(models.Model):
..
class B(models.Model):
a = models.ForeignKey(A)
value = models.IntegerField(db_index = True)
我可以找到$ code引用的 A
的任何实例> B 其中 B.value = 123
使用 A.objects.filter(b__value = 123)
。但是如何找到任何 B
的任何实例引用的 A
的实例,无需任何其他条件?我想要写 A.objects.filter(b)
,但这不会是一个有效的语法。如何写?
解决方案
如果我没有误会,你正在寻找 isnull
A.objects.filter(b__isnull = False)
-
b __
是class A
因为您在B类
中有一个ForeignKey到A类
。当您使用反向关系时,您使用小名称的类名。 -
isnull
让您过滤记录到他们的NULL
或NOT NULL
条件。
Let's assume we have the following two models:
class A(models.Model):
...
class B(models.Model):
a = models.ForeignKey(A)
value = models.IntegerField(db_index=True)
I can find any instance of A
which is referenced by B
where B.value=123
using A.objects.filter(b__value=123)
. But how do I find any instance of A
which is referenced by any instance of B
, without any further conditions? I would want to write A.objects.filter(b)
, but that would not be a valid syntax. How do I write it then?
解决方案
If I do not misunderstand, you are looking for isnull
A.objects.filter(b__isnull=False)
b__
is the back reference toclass A
since you have a ForeignKey toclass A
inclass B
. you use the class name in lowercase when you are using it in reverse relation.isnull
let you filter records acording to theirNULL
orNOT NULL
condition.
这篇关于过滤来自另一个模型的任何引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文