[Answered ]-How can I combine two fields into one in django by using serializers

1πŸ‘

βœ…

Yes, you can make a custom field:

class AgoField(serializers.Field):
    source_attrs = None

    def run_validation(self, primitive_value):
        return {
            'ago_from': primitive_value['from'],
            'ago_to': primitive_value['to'],
        }

    def get_attribute(self, instance):
        return {'from': instance.ago_from, 'to': instance.ago_to}

    def to_representation(self, value):
        return value
# serializers.py


class BannerSerializer(ModelSerializer):
    ago = AgoField()
    image = Base64ImageField()

    class Meta:
        model = Banner
        fields = ['id', 'ago', 'text', 'description', 'image', 'link']

the AgoField still requires some extra finetuning, like validators, etc. but this is the basic implementation for a "happy path".

Leave a comment