1

我有 2 张桌子:

  • 产品(ID,名称)
  • 属性(id、product_id、名称、值)

搜索产品时如何加入“属性”表2次?由于稍后分页,它们必须在一个查询中。

示例:搜索必须具有 2 个属性的产品 - 一个为name=att1, value=value1,另一个为name=att2, value=value2


源代码:

class Product(models.Model):
    product_id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=100, null=False)

class Attribute(models.Model):
    attribute_id = models.AutoField(primary_key=True)
    product = models.ForeignKey(Product, null=False)
    name = models.CharField(max_length=100, null=False)
    value = models.CharField(max_length=100, null=False)

一个不工作的查询:

Product.objects.select_related().filter('attribute__name': 'n1', 'attribute__value':'v1').filter('attribute__name': 'n2', 'attribute__value':'v2')
4

2 回答 2

1

您不需要加入他们 2 次。您可以使用 ForignKey 创建模型,然后获取相关属性集

例如 :

你创建这样的模型

class Product(models.Model):
    name = models.CharField(max_length=100)

class Attribute(models.Model):
    product = models.ForeignKey(Product)
    name = models.CharField(max_length=100)
    value = models.IntegerField()

您可以通过电话获取产品项目

item = Product.objects.get(id=xxx)

然后获取与该项目相关的所有属性列表

from django.db.models import Q

attr = item.attribute_set.filter(Q(name='name1') | Q(name='name2'))
于 2012-11-18T08:18:53.047 回答
0

使用这样的东西:

p = Product.objects.get(pk=1)
filtered = p.attribute_set.filter(name__in=['n1','n2'],value__in=['v1','v2'])
于 2012-11-18T08:49:18.267 回答