【问题标题】:Django queryset group by and count for related fieldsDjango 查询集分组和计数相关字段
【发布时间】:2021-09-24 01:03:09
【问题描述】:

我有这种关系的模型

class Product(models.Model):

    code = models.CharField(
        _("Code"),
        max_length=50,
        unique=True
    )

    name = models.CharField(
        _("Name"),
        max_length=150
    )


class ProductOption(models.Model):
    product = models.ForeignKey(Product, verbose_name=_("Product"), on_delete=models.CASCADE, related_name='options')
    vtype = models.CharField(_("Type"), max_length=50)
    text = models.CharField(_("Text"), max_length=50)

有了这个示例数据

prod1 = Product(code='1', name='Name 1')
ProductOption(product=prod1, vtype='Color', text='Blue')
ProductOption(product=prod1, vtype='Size', text='M')
ProductOption(product=prod1, vtype='Material', text='Cotton')

prod2 = Product(code='2', name='Name 2')
ProductOption(product=prod2, vtype='Color', text='Red')
ProductOption(product=prod2, vtype='Size', text='X')
ProductOption(product=prod2, vtype='Material', text='Cotton')

prod3 = Product(code='3', name='Name 3')
ProductOption(product=prod3, vtype='Color', text='Red')
ProductOption(product=prod3, vtype='Size', text='L')
ProductOption(product=prod3, vtype='Material', text='Cotton')

如何使用 ORM 从 Product 构建查询并得到此结果

例子:

Product.objects.filter(name__icontains='some text').values('options__vtype', 'options__text').annotate(count=Count())

[
    {'options__vtype': 'Color', 'options__text': 'Blue', 'count': 1},
    {'options__vtype': 'Color', 'options__text': 'Red', 'count': 2},
    {'options__vtype': 'Size', 'options__text': 'M', 'count': 1},
    {'options__vtype': 'Size', 'options__text': 'X', 'count': 1},
    {'options__vtype': 'Size', 'options__text': 'L', 'count': 1},
    {'options__vtype': 'Material', 'options__text': 'Cotton', 'count': 3},
]

我测试了很多选项,例如使用 Concat 和 Count,但我失败了。

【问题讨论】:

  • 请澄清您的具体问题或提供其他详细信息以准确突出您的需求。正如目前所写的那样,很难准确地说出你在问什么。

标签: django django-models django-queryset


【解决方案1】:

试试这个:

ProductOption.objects.values('vtype', 'text').annotate(count=Count('*'))

【讨论】:

    猜你喜欢
    • 2014-01-18
    • 2011-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-20
    • 2021-09-01
    • 2011-01-29
    • 2012-01-01
    相关资源
    最近更新 更多