如何查询ManyToManyField的对象?(不通过)

时间:2015-11-05 00:13:29

标签: python django django-queryset django-orm manytomanyfield

下面给出的是零售店的模型。

class Rack(models.Model):
    name = models.CharField(max_length=128)
    number = models.PositiveSmallIntegerField()
    categories = models.ManyToManyField(Category)


class Category(models.Model):
    name = models.CharField(max_length=128)
    code = models.CharField(max_length=3)


class Product(models.Model):
    title = models.CharField(max_length=255)
    in_stock = models.BooleanField(default=False)
    categories = models.ManyToManyField(Category)

机架:产品库存的机架。 类别:产品的类别。 产品:产品

机架可以有多个类别,同一类别可以在多个机架上。 为了便于管理,我更喜欢在管理员的机架上选择类别,所以我更喜欢这种设计。

如果有一个机架,比如No.1,我如何查询给定机架上的产品?

>> Rack.objects.get(number=1).categories.all()

[<Category: Fruits>, <Category: Vegetables>]

我不想迭代此查询集,但要进行查询以返回对象。

我的问题是,如何查询机架 上的对象尽可能优化

以便查询必须返回对象列表。

>> Rack.objects.filter( * code here to get the objects in the rack 1 * ) must returns the objects on the rack 1
[<Product: Apple>, <Product: Orange>, <Product: Cucumber>, <Product: Carrot>, <Product: Green Chillie>, <Product: Onion>, <Product: Grapes> ]

由于

1 个答案:

答案 0 :(得分:1)

您最好的选择可能是使用through model。如果你不想这样做,我会尝试这样的事情:

categories = Rack.objects.get(number=1).categories.all().values_list('name', flat=True)
Product.objects.filter(categories__name__in=categories)

另外,你的意思是:

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

是:

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

就像你的Rack模特一样?

相关问题