【问题标题】:Django ORM search product but group by categoryDjango ORM 搜索产品但按类别分组
【发布时间】:2021-05-03 08:38:59
【问题描述】:

我正在尝试实现一个搜索系统,它将按类别显示所有结果。

这些是我的模型。

class Category(models.Model):

    name = models.CharField(max_length=255)
    slug = models.SlugField(
        verbose_name="slug",
        allow_unicode=True,
        max_length=255,
        help_text='A slug to identify posts by this category',
    )

  
class Product(models.Model):
   

    name = models.CharField(
        max_length=255,
        verbose_name=_('Product Name'),
    )
    categories = ManyToManyField("product.Category", related_name="product_category")

   

我需要在前端/模板中按类别呈现所有项目组,但查询将基于产品名称。

prod_cat = Category.objects.annotate(
        filtered_product=Product.objects.filter(name__incontains="My Search Term goes There")
)

它根本不工作。

我也可以这样查询:

result = []
prod_cat = Category.objects.all()
for cat in prod_cat:
    p = cat.product_category.filter(name__incontains='My Another Search Term')
    result.append(p)

但我认为它不是分组依据,它是基于每个列表的列表产品,这样我不能将模板上的类别名称命名为类别标题。

有没有人知道我如何按每个类别查询和分组?

【问题讨论】:

  • 您说按类别分组,但您想搜索产品?您是否要按照数据库术语执行 join ? A Group by 意味着需要执行一些聚合,这不是您想要的。
  • 是的,我想根据具体的词条搜索产品,所有的搜索结果都会按类别显示。
  • 附带说明,您需要更多查询才能以这种方式进行操作(根据多对多分组显示搜索结果)。考虑只显示结果而不按类别分组,并提供仅搜索特定类别的选项。

标签: django django-models django-rest-framework django-orm


【解决方案1】:

如果您将result.append(p) 更改如下,您当前的解决方案将很容易工作:

result.append({'category': cat, 'products': p})

现在在模板中:

{% for entry in result %}
    {{ entry.category.name }}
    {% for product in entry.products %}
        {{ product.name }}
    {% endfor %}
{% endfor %}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-06
    • 1970-01-01
    • 1970-01-01
    • 2017-11-13
    • 1970-01-01
    相关资源
    最近更新 更多