过滤来自另一个模型的任何引用 [英] Filtering by any reference from another model

查看:128
本文介绍了过滤来自另一个模型的任何引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们假设我们有以下两个模型:

  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 to class A since you have a ForeignKey to class A in class B. you use the class name in lowercase when you are using it in reverse relation.
  • isnull let you filter records acording to their NULL or NOT NULL condition.

这篇关于过滤来自另一个模型的任何引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆