1

Как можно в DRF изменить имена полей модели и добавить новые (для отображения в API (json)), не меняя при этом саму модель?

1 ответ 1

1

Как-то так?

class Person(Model):
    name = CharField(...)
    slug = CharField(...)

    def get_name(self):
        return self.name + self.slug


class PersonSerializer(ModelSerializer):
    full_name = serializers.CharField(source='get_name', read_only=True)

    class Meta:
        model = Person
        fields = ('slug', 'full_name')

Изменить поле еще можно, переопределив метод to_representation:

def to_representation(self, obj):
    old_repr = super().to_representation(obj)
    old_repr['NEW FIELD'] = old_repr['OLD FIELD']
    return old_repr

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.