简体   繁体   English

两种模型的Django queryset过滤器

[英]Django queryset filter from two models

In my Django app I have two model and I don't know how to do a query for select the right record. 在我的Django应用程序中,我有两个模型,而且我不知道如何查询选择正确的记录。 This is the code: 这是代码:

class tab1 (models.Model):
    id_tab1 = models.AutoField(primary_key=True)
    name = models.CharField(max_length=50)

class tab2 (models.Model):
    id_tab1 = models.ForeignKey(tab1)
    type = models.IntegerField()

I would like to select the tab1 records that have tab2.type equal to some condition. 我想选择具有等于某些条件的tab2.type的tab1记录。 How can I do this in Django? 如何在Django中执行此操作?

your_queryset = tab1.objects.filter(tab2__type=value)

See the relevant documentation here In a few words: you can span relationships either way (ie from each end of a foreign key). 简而言之,请参见此处的相关文档:您可以以任何一种方式(即从外键的每一端)扩展关系。 The condition is specified in the named argument to filter(). 条件在filter()的命名参数中指定。 The one I suggested above is the simplest one (ie equality), but there are quite a few more (eg startswith, contains, etc). 我上面建议的是最简单的一个(即相等),但是还有很多(例如,startswith,contains等)。 Please read here 在这里阅读

Consider you have values 1,2 stored for the field type . 考虑您为字段type存储了值1,2。 The following illustrates the one way of achieving your need for type=1 . 下面说明了满足type=1需求的一种方法。

filtered_objs = tab1.objects.filter(type=1)
tab2.objects.filter( tab1__in=filtered_objs)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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