【问题标题】:Iterate over all categories and all products each category遍历所有类别和每个类别的所有产品
【发布时间】:2020-02-10 21:03:25
【问题描述】:

我正在尝试创建一个页面,我可以在其中循环遍历我的所有类别以及每个类别中的所有产品。

类似这样的:

Category 1:
product1
product2
product3

Category 2:
product1
product2
product3

Category 3:
product1
product2
product3

views.py

def model_categories_view(request):
    context = {
        "categories": ProductCategory.objects.all(),
        "models": ProductModel.objects.filter(???),
    }
    return render(request=request, template_name='main/categories.html', context=context)

categories.html

{% for category in categories %}

    <h1>{{category.title}}</h1>
    {% for model  in models %}
        {{model.title}}
    {% endfor %}

{% endfor %}

models.py

class ProductModel(models.Model): 
    title = models.CharField(max_length=80)
    category = models.ManyToManyField(ProductCategory)
    model_slug = AutoSlugField(null=True, default=None,
                         unique=True, populate_from='title')

    class Meta:
        verbose_name_plural = "Models"

    def __str__(self):
        return self.title


class ProductCategory(models.Model):
    title = models.CharField(max_length=50)
    category_slug = AutoSlugField(null=True, default=None,
                         unique=True, populate_from='title')

    class Meta:
        verbose_name_plural = "Product Categories"

    def __str__(self):
        return self.title

如何列出当前正在迭代的类别的所有模型?

【问题讨论】:

  • 可以分享一下相关型号吗?
  • @WillemVanOnsem 完成
  • 可能BoatCategory 是ProductCategory 或反之亦然?
  • 是的,我正在尝试简化我的模型

标签: django django-models django-templates django-views


【解决方案1】:

您可以通过.productmodel_set获取相关产品的查询集。因此,您可以将模板编写为:

{% for category in categories %}
    <h1>{{ category.title }}</h1>
    {% for product in category.productmodel_set.all %}
        {{product.title}}
    {% endfor %}
{% endfor %}

为确保高效完成此操作,您可以利用.prefetch_related(..) [Django-doc] 有效地获取给定ProductCategorys 的所有相关Products:

def model_categories_view(request):
    context = {
        "categories": ProductCategory.objects.prefetch_related('productmodel')
    }
    return render(
        request=request,
        template_name='main/categories.html',
        context=context
    )

注意:一般型号有没有Model后缀,所以你最好将ProductModel重命名为Product。

【讨论】:

  • 我不确定 'productmodel' 来自哪里。
  • 从ManyToMany从ProductModel到ProductCategory是ForeignKey的related_name_query。默认情况下,这是“snake_case”中模型的名称。
  • 我收到Cannot find 'productmodel' on ProductCategory object, 'productmodel' is an invalid parameter to prefetch_related() 也许这是由stackoverflow.com/questions/60117918/… 引起的,我已经尝试解决这个问题一段时间了..
  • @GTA.sprx:通常它应该暗示关系。如果您更改了模型的名称,那么这些名称当然会有所不同。
  • 它没有提出任何建议。我按照您的说明做了所有事情,但我仍然收到 AttributeError Cannot find 'productmodel' on ProductCategory object, 'productmodel' is an invalid parameter to prefetch_related()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-28
  • 2018-05-14
  • 1970-01-01
  • 2015-03-20
  • 1970-01-01
相关资源
最近更新 更多