How to get all instances in serializer method field

Viewed 4687

How to get all instances in serializer method field

I have a serializer method field and I am passing list data in the form of context to serializer like below.

name_list = [ "abc", "def",....]
obj_list = abc.objects.all() 

Serializer = abcSerializer (obj_list, context=name_list, many=True)

    class abcSerializer (serializers.ModelSerializer):
        xyz = serializers.SerializerMethodField ("getXYZ", read_only=True)

        class Meta:
            model = abc

            def getXYZ (self, data):
                # here I want all instanceses, but I got only one instance in data. 

I want to attach name_list data one by one to instace data with same index? How I can get all instanceses in my serializer method field?

2 Answers

Why do you need all instances? If you want to manipulate something in all instances, better do it before passing it as argument in Serializer. If you want to get indivisual instance, you should get the value in data parameter. But your indentations are wrong. Try like this:

class abcSerializer (serializers.ModelSerializer):
    xyz = serializers.SerializerMethodField("getXYZ")

    class Meta:
       model = abc

    def getXYZ(self, data):
       print(data) # it will print a instance of abc
       return value_based_on_data

Update

Then I think you should try like this:

First update serializer class:

class abcSerializer (serializers.ModelSerializer):  # use PascalCase for naming classes
    xyz = serializers.ReadOnlyField()

    class Meta:
        model = abc
        fields = '__all__'   # use PascalCase for naming classes

Then use the following code to get values of xyz:

obj_list = []
for i, item in enumerate(abc.objects.all()):
    item.xyz = name_list[i]
    obj_list.append(item)

abcSerializer(obj_list, many=True).data

After dig deep into debugging I realized that I should share my findings with the community. Look at the below line:

Serializer = abcSerializer (obj_list, context=name_list, many=True)

Here many=True make's abcSerializer to list serializer, according to rest framework documentation in list serializer we can access all objects of queryset in update method like below

    class BookListSerializer(serializers.ListSerializer):
        def update(self, instance, validated_data):
            # Maps for id->instance and id->data item.
            book_mapping = {book.id: book for book in instance}
            data_mapping = {item['id']: item for item in validated_data}

            # Perform creations and updates.

I found that we can also access all objects of queryset in any method even in serializerMethodField using below syntax

def getXYZ (self, data):
    objects = self.instance
Related