MiniGunnR MiniGunnR - 28 days ago 8
reST (reStructuredText) Question

How to show depth of a single field in Django Rest Framework?

I am using

depth = 1
on my serializer to show details of a foreign key field. However, it is also showing details of another foreign key field which I don't really need. How do I show the details of one field but not the other one?

Answer

Just for your reference

Suppose you have three models:

class User(model.Model):
    username = model.CharField('username', max_length=10)

class Question(model.Model):
    title = models.CharField('title', max_length=10)

class Answer(model.Model):
    user = model.ForeignKey(User)
    question = model.ForeignKey(Question)
    body = model.TextField('the answer body')

And you need to serialise Answer, with showing the detail of Question, but not showing the detail of User, then you could define your serialisers like that:

class QuestionSerializer(serializers.ModelSerializer):
    class Meta:
        model = Question
        exclude = []

class AnswerSerializer(serializers.ModelSerializer):
    question = QuestionSerializer(many=False, read_only=True)
    class Meta:
        model = Answer
        exclude = []

when you serialise Answer with AnswerSerializer, you will notice that question field is serialise at the same time, however user field is still an integer without serialising.

If you need to serialise a foreign key, you can define a field in the serializer explicitly, and the field name equal to the field name in model, and the value is equal to Foreign key model serializer. When the model is serialise, Answer in this case, the foreign key field, question for this case, will be "expanded" with QuestionSerializer, and other foreign key fields still keep the origin foreign key value, user in this case, if you haven't explicitly defined a serializer field in the serializer.

Hope it would help.