I need some advice for making a query in Django (DRF).
I'm trying to make a queryset for Products, where every Product gets a field "images" with all the Images (Files) for that product (coupled using ProductImage model), but I can't figure out how to add the field.
Below is my ProductViewSet
class ProductViewSet(viewsets.ModelViewSet):
serializer_class = ProductSerializer
queryset = Product.objects.all()
def get_queryset(self):
queryset = Product.objects.all()
product_list = []
# iterate over all products
for product in queryset:
# find Image ids for product
image_ids = list(ProductImage.objects.filter(product=product.id).values_list('image', flat=True))
images = []
# iterate over images and add to images list
for image_id in image_ids:
image = list(File.objects.filter(id=image_id).all())
images.append(image)
# add images field to product
# product['images'] = images # "TypeError: 'Product' object does not support item assignment"
product.images = images # Doesn't do anything.
# add product to product list
product_list.append(product)
return product_list
I've tried to do the following to add the field "images":
product['images'] = images
which gives the error "TypeError: 'Product' object does not support item assignment"
product.images = images
which doesn't do anything...
Could anyone point me in the right direction? Any tips on how to make this query in a better way are also welcome!