M
M
MaxEpt2017-10-17 13:29:12
Django
MaxEpt, 2017-10-17 13:29:12

How to write serializer correctly?

Good afternoon!
For example, there are two models:

class ModelA(models.Model):
   name = models.CharField("ФИО", max_length=100)
   titke = models.CharField("тайтл", max_length=100)

class ModelB(models.Model):
    name = models.CharField("Имя", max_length=100)
    modela = models.ForeignKey(ModelA)

There is such a Serializer
class ModelASerializater(serializaters.HyperLinkModelSerialzater):
     class Meta:
            model = ModelA
            fields = (...)

class ModelBSerializater(serializers.ModelSerializer):
    modela = ModelASerializater
    class Meta:
        model = ModelB
        fields = (...)

ModelBSerializater will return modela as nested json with all fields. I only need one field. How can I do that ? where can I even read about serializers in Russian?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Pavel Aksenov, 2017-10-17
@hellmin

class ModelBSerializater(serializers.ModelSerializer):
    name_a = serializers.ReadOnlyField(source='modela.name')
    class Meta:
        model = ModelB
        fields = (..., name_a)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question