如何在ORM中获取具有某些外键关系的对象?

时间:2020-08-27 09:46:49

标签: django django-models

假设我们有一个产品模型:

class Product(models.Model):    
    name = models.Charfield()

以及定义了可能的属性(例如“价格”,“颜色”,“重量” ...)的属性模型:

class Property(models.Model):
    name = models.CharField()

我们将产品属性保留在单独的模型中:

class ProductProperty(models.Model):    
    property = models.ForeignKey(Property)    
    product = models.ForeignKey(Product)   
    value = models.Charfield()

我想获得具有某些属性的产品对象。例如,仅当在ProductPropery表中为它们定义了“价格”和“颜色”时,我才想获取对象。

我获得了所需的属性作为对象,但是我无法解决如何获得具有所有给定属性的产品。

换句话说,我正在寻找这样的东西:

properties = Property.objects.filter(Q(name__contains="Price") | Q(name__contains="Color")) #this could return one or multiple property objects
products = properties.productproperty_set.product_set # imaginary line I made up to show what I want to get

我只能想到遍历属性和相关ProductProperty的内部循环,以使其产品创建多个列表,然后创建一个由通用元素(每个列表中包含的产品)组成的列表。

0 个答案:

没有答案