[英]Querying through four models in Django
I have a data model similar to this (simplified): 我有一个与此类似的数据模型(简化):
class Mobility(models.Model):
pass
class Transfer(models.Model):
mobility = models.ForeignKey(Mobility)
class Organism(models.Model):
pass
class TransferLine(models.Model):
transfer = models.ForeignKey(Transfer)
organism = models.ForeignKey(Organism)
I have an instance of Mobility
and an instance of Organism
, and I'd like to get all the TransferLine
instances that are related to both (to the Organism
directly, and to the Mobility
through the Transfer
). 我有一个
Mobility
实例和一个Organism
实例,并且我想获取所有与两者都相关的TransferLine
实例(直接与Organism
以及与通过Transfer
的Mobility
)。
This question differs from this other question in that in my case, I need to go through two relations and there's also a compound condition. 这个问题与另一个问题的不同之处在于,就我而言,我需要经历两个关系,并且还有一个复合条件。
Just use the double-underscore notation to make lookups that span relationships. 只需使用双下划线符号即可进行跨越关系的查找。 In this case, it could be done like this:
在这种情况下,可以这样进行:
transfer_lines = TransferLine.objects.filter(transfer__mobility=mobility,
organism=organism)
另一种方法是使用ForeignKey
反向关系 :
tlines = my_organisam.transferline_set.filter(transfer__mobility=my_mobility)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.