darkhorse
darkhorse

Reputation: 8722

How to save an object to be re-used in Django Rest Framework Serializer Method Fields?

The situation is as follows:

Kinda like this:

class ProductSerializer(serializers.ModelSerializer):
    field_1 = serializers.SerializerMethodField()
    def get_field_1(self, obj):
        content = generate_content(obj)
        return content.field_1

    field_2 = serializers.SerializerMethodField()
    def get_field_2(self, obj):
        content = generate_content(obj)
        return content.field_2

As you can see, both the methods is calling the same function, with the same argument and therefore getting the exact same result. The generate_content function is very large, so I feel it would be best if I could save the content once, and use that to generate the two fields. How can I pull this off? Thanks!

Upvotes: 0

Views: 195

Answers (1)

aliva
aliva

Reputation: 5720

you can simply put the generated content within a variable, when generate_content is called check if that variable exists or not:

class ProductSerializer(serializers.ModelSerializer):
    def __init__(self, *args, **kwargs):
        super(ProductSerializer, self).__init__(*args, **kwargs)
        self.generated_content = None

    def generate_content(self, obj):
       if self.genretated_content:
           return self.genretated_content
       self.genretated_conten = 1 # gernerate here
       return self.genretated_content

    field_1 = serializers.SerializerMethodField()
    def get_field_1(self, obj):
        content = generate_content(obj)
        return content.field_1

    field_2 = serializers.SerializerMethodField()
    def get_field_2(self, obj):
        content = generate_content(obj)
        return content.field_2

Upvotes: 2

Related Questions