【问题标题】:How to define the query filter for the following situation?如何定义以下情况的查询过滤器?
【发布时间】:2016-03-15 06:55:11
【问题描述】:

我已将我的模型定义如下,如何定义一个查询来过滤指定名称列表中关联的 Test_Product 的产品名称的 Sanity_Test 集?非常感谢

例如:

  1. Sanity_Test_A 包含 Test_Product_A(产品名称为 A)、Test_Product_B(产品名称为 B)

  2. Sanity_Test_B 包含 Test_Product_C(产品名称为 A)、Test_Product_D(产品名称为 C)

  3. 我想过滤 Sanity_Test 记录列表,它的 Test_Product 记录的 Product name 是 A

APP : CT.model

class Sanity_Test(models.Model):

    build        = models.OneToOneField('CI.Build')                                                           
    system_test  = models.ForeignKey(System_Test,null=True,blank=True)

    ......


class Test_Product(models.Model):

    product     = models.ForeignKey('CI.Product',verbose_name='Product')            
    sanity_test = models.ForeignKey(Sanity_Test)

    ......


# APP : CI.model 
class Product(models.Model):

    name = models.CharField(max_length=255,unique=True)

    ......

The Test_Product Record Info

【问题讨论】:

    标签: python django django-models django-queryset


    【解决方案1】:

    您也可以使用reverse relationships 仅通过一个查询来完成:

    sanity_test = Sanity_Test.objects.filter(test_product__product__name='A')
    

    【讨论】:

    • 是的,因为test_product 有一个指向sanity_test 的外键。它被称为reverse relationship。来自文档:“它也可以反向工作。要引用“反向”关系,只需使用模型的小写名称即可。”
    【解决方案2】:

    你可以这样做:

    sanity_test = [ test_product.sanity_set for test_productin Test_Product.objects.filter(product__name='A')]
    

    这会获取所有产品名称为A的Test_Product对象,然后将对应的sanity_test对象添加到列表中

    【讨论】:

    • 这就是我的预期,非常感谢您的热心帮助:)
    猜你喜欢
    • 1970-01-01
    • 2017-09-05
    • 1970-01-01
    • 1970-01-01
    • 2018-06-27
    • 2010-12-27
    • 1970-01-01
    • 1970-01-01
    • 2016-09-11
    相关资源
    最近更新 更多