在 Django 查询中合并重复值
Merge duplicate values in django query
我有一个 SQL 查询,但我想知道如何以 Django 格式 (PostgreSQL) 编写。我是 django 的新手:)
假设,我们有这样的table数据。
1: Color: Pink, Size: 1M
2: Color: Pink, Size: 2M
3: Color: Red, Size: 1M
4: Color: Red, Size: 3M
5: Color: Yellow, Size: 2M
期待输出
Pink
Red
Yellow
I'm getting output with the below query. But I want to know, how can I query & merge duplicate values in django
// id = product_id
colors = Variants.objects.raw('SELECT * FROM product_variants WHERE product_id=%s GROUP BY color_id',[id])
型号:
class Variants(models.Model):
title = models.CharField(max_length=100, blank=True,null=True)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
color = models.ForeignKey(Color, on_delete=models.CASCADE,blank=True,null=True)
size = models.ForeignKey(Size, on_delete=models.CASCADE,blank=True,null=True)
image_id = models.IntegerField(blank=True,null=True,default=0)
quantity = models.IntegerField(default=1)
price = models.DecimalField(max_digits=12, decimal_places=2,default=0)
Variants model
您可以查询:
Color.objects.filter(variants__product_id=<i>productid</i>)<b>.distinct()</b>
这将给出 Color
个对象,其中有给定产品的变体。 .distinct()
[Django-doc] 调用用于最多检索每种颜色一次。
我有一个 SQL 查询,但我想知道如何以 Django 格式 (PostgreSQL) 编写。我是 django 的新手:)
假设,我们有这样的table数据。
1: Color: Pink, Size: 1M
2: Color: Pink, Size: 2M
3: Color: Red, Size: 1M
4: Color: Red, Size: 3M
5: Color: Yellow, Size: 2M
期待输出
Pink
Red
Yellow
I'm getting output with the below query. But I want to know, how can I query & merge duplicate values in django
// id = product_id
colors = Variants.objects.raw('SELECT * FROM product_variants WHERE product_id=%s GROUP BY color_id',[id])
型号:
class Variants(models.Model):
title = models.CharField(max_length=100, blank=True,null=True)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
color = models.ForeignKey(Color, on_delete=models.CASCADE,blank=True,null=True)
size = models.ForeignKey(Size, on_delete=models.CASCADE,blank=True,null=True)
image_id = models.IntegerField(blank=True,null=True,default=0)
quantity = models.IntegerField(default=1)
price = models.DecimalField(max_digits=12, decimal_places=2,default=0)
Variants model
您可以查询:
Color.objects.filter(variants__product_id=<i>productid</i>)<b>.distinct()</b>
这将给出 Color
个对象,其中有给定产品的变体。 .distinct()
[Django-doc] 调用用于最多检索每种颜色一次。