如何獲取與“ProductImage”中的外鍵欄位關聯的所有物件。所以我在“ProductImage”中有一個“產品”模型的多個影像,我如何獲得所有相關的影像。目前,我收到一個錯誤“MultipleObjectsReturned at /shop/product-slug”idk 我做錯了什么,如果有人能提供幫助將不勝感激!謝謝!
模型.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/')
網址.py
path("<slug:slug>", views.detail_view, name="detail_view"),
視圖.py
def detail_view(request, slug):
products = Product.objects.get(slug=slug)
productimg = ProductImage.objects.get(product=products)
uj5u.com熱心網友回復:
要在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
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/450242.html
上一篇:如何查詢和附加與其他模型的多對多關系鏈接的用戶電子郵件串列
下一篇:TypeError:欄位“金額”需要一個數字,但得到了datetime.datetime(2022,3,27,10,46,51,801087,tzinfo=datetime.timezone.utc)
