How do I get all the objects associated with the foreignkey field in "ProductImage". So I've multiple images for one "Product" model in "ProductImage", how do I get all of the associated ones. Currently, I'm getting an error "MultipleObjectsReturned at /shop/product-slug" idk what I'm doing wrong, would appreciate it a lot if someone can help! thx!
models.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)
CodePudding user response:
To find all related objects in Django, use filter
method that returns a queryset, use get
method instead if you know there is only one object that matches your query.
Read more in the official Django documentation
Another tip: when using get
, it's highly recommended you surround it with try
except
block in order to make your code brokenless if the selected object is not found. Your code could be like that :
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