【发布时间】:2019-09-10 20:05:37
【问题描述】:
我在我的 django 模型中存储了一个产品列表,每个产品附加了多个图像作为外键。我正在尝试在我的 django 视图中检索所有产品及其各自的图像,以便我可以在屏幕上打印它们。但是,无论我做什么,我都会在赋值错误之前不断获取局部变量“产品”引用。
Models.py:
class product(models.Model):
title = models.CharField('', max_length=100, db_index=True)
price = models.CharField('', max_length=100, db_index=True)
description = models.CharField('', max_length=100, db_index=True)
class productimage(models.Model):
product = models.ForeignKey(product, on_delete=models.CASCADE)
product_images = models.FileField(blank=True)
views.py:
from django.shortcuts import render
from selling.models import product
from selling.models import productimage
from django.shortcuts import redirect
from django.template import loader
template = loader.get_template("selling/shop.html")
if product.objects.exists():
products = product.objects.all()
for product in products:
productimages = product.productimage_set.all()
for productimage in productimages:
imageurl = productimage.product_image.url
context = {
"products" : products,
"productimages" : productsimages,
}
【问题讨论】:
-
在 Django 中,模型类以大写字母开头是一个非常严格的约定。如果您在此处遵循此操作,您可能会更早注意到您的错误。