Django:列出页面中每个类别的产品 [英] Django: List Products of each Categories in a page

查看:58
本文介绍了Django:列出页面中每个类别的产品的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个类别,我想按以下格式列出每个类别的产品(类别是产品的 FK):

I have a few categories and I would like to list the products per category in the format below (categories is an FK to products):

类别 1

一堆产品

....

类别 N

一堆产品

我尝试了很多方法,但到目前为止我只得到类别而不是产品以显示在我的 HTML 中.

I have tried many ways but so far I only get the categories but not the products to show in my HTML.

模型.py

class Category(models.Model):
    title = models.CharField(max_length=225)
    slug = models.SlugField(unique=True, blank=True, null=True)

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('category_detail', kwargs={'slug': self.slug})

    @property
    def get_products(self):
         return Products.objects.filter(category=self.title)

class Products(models.Model):
    title = models.CharField(max_length=225)
    image = models.ImageField(upload_to=upload_image_path, null=True, blank=True)
 blank=True, on_delete=models.CASCADE)
    categories = models.ForeignKey(Category, related_name='Category', blank=True, on_delete=models.CASCADE) #this
    gender = models.CharField(max_length=20, choices=GENDER_CHOICES, default="male")

    objects = ProductManager()

    def get_absolute_url(self):
        return reverse('product_detail', args=(self.id,))

    def __str__(self):
        return self.title

views.py

def categories_m(request):
    query_Set = models.Category.objects.all()
    page = request.GET.get('page', 1)
    paginator = Paginator(query_Set, 20)
    try:
        cat = paginator.page(page)
    except PageNotAnInteger:
        cat = paginator.page(1)
    except EmptyPage:
        cat = paginator.page(paginator.num_pages)
    return render(request, 'products/categories.html', {'categories': cat})

html

{% extends 'base.html' %}

{% block content %}
{% for category in categories %}
    <h1>{{ category }}</h1>
    {% for product in categories.get_products %}
        <p>{{ product }}</p>
    {% endfor %}
{% endfor %}
{% endblock %}

推荐答案

它应该是 category 而不是 categories 在你的模板中.并在您的模型中按类别标题过滤产品.

It should be category instead of categories in your template. And in your model filter products by category title.

@property
def get_products(self):
     return Products.objects.filter(categories__title=self.title)


{% extends 'base.html' %}

    {% block content %}
        {% for category in categories %}
        <h1> {{category}} </h1>

        {% for product in category.get_products %}
            <p> {{product}} </p>
        {% endfor %}

        {% endfor %}
    {% endblock %}

这篇关于Django:列出页面中每个类别的产品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆