2

我有这样的模型:

class Category(Model):
    ...
    type = models.CharField(max_length=255, choices=settings.CATEGORIES)

class Product(models.Model):
    ...
    categories = models.ManyToManyField(Category)

我有用户输入的类别列表(格式是任意的):

c = [<Category: G, type: producer>, <Category: L, type: producer>, <Category: Teen, type: age>, <Category: Man, type: sex>]

现在我想拥有所有类别中的“G”或“L”类型为“producer”、“Teen”类型为“age”和“Man”类型为“sex”的产品。例如,我正在做下一个查询集:

Product.objects.filter(Q(categories=c[0])|Q(categories=c[1]), Q(categories=c[2]), Q(categories=c[3])

有这样的查询:

SELECT "shop_product"."id", "shop_product"."title", "shop_product"."description",
"shop_product"."price", "shop_product"."code", "shop_product"."stored_count",
"shop_product"."sold_count", "shop_product"."added_date" FROM "shop_product"
INNER JOIN     "shop_product_categories" ON ("shop_product"."id" =   
"shop_product_categories"."product_id")    WHERE 
(("shop_product_categories"."category_id" = 1 OR 
"shop_product_categories"."category_id" = 2) AND    
"shop_product_categories"."category_id" = 4 AND 
"shop_product_categories"."category_id" = 6)

我至少有一个符合此类要求的对象,但 queryset 什么也不返回。有什么建议吗?

4

1 回答 1

2

您需要进行级联过滤,否则当前选择将同时返回"shop_product_categories"."category_id"值为 1/2 和 4 和 6 的所有产品...这是一个示例查询集,它将返回您想要的内容:

Product.objects.filter(categories__in=c[0:2])
               .filter(categories=c[2])
               .filter(categories=c[3])
               .distinct()

生成这样的SQL:

SELECT DISTINCT "test1_product"."id" FROM "test1_product" INNER JOIN "test1_product_categories" ON ("test1_product"."id" = "test1_product_categories"."product_id") 
    INNER JOIN "test1_product_categories" T4 
        ON ("test1_product"."id" = T4."product_id")
    INNER JOIN "test1_product_categories" T6 
        ON ("test1_product"."id" = T6."product_id") 
WHERE ("test1_product_categories"."category_id" IN (1, 2) 
    AND T4."category_id" = 3 
    AND T6."category_id" = 4 )
于 2012-07-06T10:50:58.723 回答