我有这样的模型:
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"类型为"生产者","青少年"为"年龄"类型和"男人"类型为"性别"的所有产品。例如,我正在做下一个查询集:
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)
我至少有一个对象,适合这样的要求,但查询集不返回任何内容。有什么建议吗?
你需要做级联过滤,否则当前选择会同时返回所有值为 1/2 和 4 和 6 的"shop_product_categories"."category_id"
产品......下面是一个示例查询集,它将返回所需的内容:
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 )