如何获取"中与foreignkey字段关联的所有对象;ProductImage";。所以我有多个图像作为一个";产品";模型在";ProductImage";,我如何获得所有相关的。目前,我收到一个错误";MultipleObjectsReturn at/shop/product slug";我知道我做错了什么,如果有人能帮忙,我将不胜感激!thx!
型号.py
class Product(models.Model):
name = models.CharField(max_length=150)
description = models.TextField()
image = models.ImageField(null=True, blank=True)
class ProductImage(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE)
name = models.CharField(max_length=50)
image = models.ImageField(null=True, blank=True, upload_to='productimg/')
urls.py
path("<slug:slug>", views.detail_view, name="detail_view"),
views.py
def detail_view(request, slug):
products = Product.objects.get(slug=slug)
productimg = ProductImage.objects.get(product=products)
要在Django中查找所有相关对象,请使用返回查询集的filter
方法,如果您知道只有一个对象与您的查询匹配,请使用get
方法。
阅读官方Django文档中的更多信息
另一个提示:在使用get
时,强烈建议您用try
except
块包围它,以便在找不到所选对象的情况下使代码无中断。你的代码可能是这样的:
def detail_view(request, slug):
try:
products = Product.objects.get(slug=slug)
productimg = ProductImage.objects.filter(product=products)
except Product.DoesNotExist as e:
print(f"My error {e}")
# ... other error handling
for image in productimg :
# your logic here