1

I have a model with multiple fields but I only want to expose some or a combination of them. For example the model has opening_time=12:00 and closing_time=18:00 and I want to return the field opening_hours=[12:00, 18:00] to the JSON.

This is just an example, but I have also some other fields to combine into one in the return JSON. How can I do this? Is there a way to use a ModelSerializer?

1 Answer 1

1

Read more abuot SerializerMethodField.

You could do something like:

class StoreSerializer(serializers.ModelSerializer):
    opening_hours = serializers.SerializerMethodField()

    class Meta:
        model = Store
        fields = ('opening_hours', )

    def get_opening_hours(self, store_instance):
        opening_time = self.format_time(store_instance.opening_time)
        closing_time = self.format_time(store_instance.closing_time)
        return [opening_time, closing_time]

    def format_time(self, dt):
        return dt.strftime('%H:%M')
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, It was just what I needed ! It's working now

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.