Django:如何列出类别的产品

时间:2019-03-26 18:54:46

标签: django

尝试使用related_name属性获取一对多关系的孩子。

到目前为止我尝试过的方法不起作用:

models.py

class Category(models.Model):
    name = models.CharField(max_length=30, unique=True)
    slug = models.SlugField(max_length=30, unique=True)

class Product(models.Model):
    name = models.CharField(max_length=255, unique=True)
    slug = models.SlugField(max_length=30, unique=True)
    category = models.ForeignKey(
        Category,
        related_name='products',
        on_delete=models.PROTECT,
        default=1
    )

views.py

from django.shortcuts import render, get_object_or_404
from Shop.models import Category

def product_list(request, slug):
    category = get_object_or_404(Category, slug=slug)
    products = category.products.all()
    context = {
        'customCSS': '/static/css/product_list.min.css',
        'title': category.name,
    }
    return render(request, template, context)

product_list.html

{% block content %}
    <ul>
    {% for product in products %}
        <li>{{ product.name }}</li>
    {% endfor %}
    </ul>
{% endblock %}

2 个答案:

答案 0 :(得分:1)

您没有在上下文中传递产品。像这样将它们传递给模板。

products = category.products.all()
context = {
    'customCSS': '/static/css/product_list.min.css',
    'title': category.name,
    'products': products,
}

答案 1 :(得分:0)

您传递给context的{​​{1}}不包含render,因此自然无法呈现products。包括它,代码应该起作用:

products