Home > database >  Django (REST Framework) - How to add fields to queryset iteration
Django (REST Framework) - How to add fields to queryset iteration

Time:01-04

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!

CodePudding user response:

Does your 'Product' model have an existing 'images' field with the correct data type?

If not, you won't be able to update it with a list of FileObjects.

A better solution might be a many-to-one model relationship between 'ProductImage' and 'Product'.

Then, Django will be better able to automagically return your images through the ORM rather than complicated bespoke queries. https://docs.djangoproject.com/en/4.0/topics/db/examples/many_to_one/

CodePudding user response:

It's hard to give an exact answer without seeing the other models, but if you write a more robust query, and use annotate, the annotated fields will be accessible on both the filtersets and serializers.

CodePudding user response:

try to use a dict, product_list = {} product_list[product] = images

remove

        product.images = images # Doesn't do anything.

        # add product to product list
        product_list.append(product)
  •  Tags:  
  • Related