Django ManyToManyField过滤参数?

时间:2012-07-06 09:05:13

标签: python django django-models manytomanyfield

我有这样的模特:

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什么也没有返回。有什么建议吗?

1 个答案:

答案 0 :(得分: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 )