是否在一个html表中的产品下显示产品属性?

2024-10-04 11:28:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一张展示所有产品的桌子。我想显示每个产品名称的产品属性。是否可以在如下所示的一个表中执行此操作

Product Table

多谢各位

型号.py

class Product(models.Model):
    name = models.CharField(max_length=60, unique=True)
    attribute = models.ManyToManyField(ProductAttribute)

class ProductAttribute(models.Model):
    property = models.CharField(max_length=20) # eg. "resolution"
    value = models.CharField(max_length=20) # eg. "1080p"

file.html

{% for product in products %}
<tr>                                            
    <td style="font-weight:bold">{{ product.name }}</td>
    
    <td>{{ product.productattribute }}</td>                                       
</tr>
{% endfor %}

视图.py

@login_required(login_url="/login/")
def productlist_details(request, shop_id, productlist_id):
    shop = Shop.objects.get(pk=shop_id)   
    products = Product.objects.all()
    productattributes = ProductAttribute.objects.all()
   
    context = {
                'shop': shop,                 
                'products': products,
                'productattributes': productattributes,                                       
            }            
    return render(request, 'productlist_details.html', context)

Tags: idobjects产品modelsloginproductshoplength
2条回答

试试这个

{% for product in products %}
<tr>                                            
<td style="font-weight:bold">{{ product.name }}</td>

<td>{{ product.attributes.property }}</td>                                       
</tr>
{% endfor %}

使用ifchanged标记(https://docs.djangoproject.com/en/3.1/ref/templates/builtins/#ifchanged),可以执行以下操作:

{% for product in products %}
    <tr>                                            
        <td style="font-weight:bold">{{ product.name }}</td> 
    </tr>

    {% for attribute in product.attributes.all %}
    <tr>
        <td>{{ attribute.property  }}</td>                                       
    </tr>
    {% endfor %}
{% endfor %}

相关问题 更多 >