简体   繁体   English

如何在Django Rest Framework中显示单个字段的深度?

[英]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. 我在序列化程序上使用depth = 1来显示外键字段的详细信息。 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? 如何显示一个字段的详细信息,而不显示另一个字段?

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: 并且您需要序列化Answer ,并显示Question的详细信息,而不显示User的详细信息,然后可以这样定义序列化器:

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. 当使用AnswerSerializer序列化Answer时,您会注意到question字段同时被序列化,但是user字段仍然是未序列化的整数。

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. 如果需要序列化外键,则可以在序列化程序中显式定义一个字段,该字段名等于model的字段名,并且该值等于外键模型序列化程序。 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. 当模型是串行化处理, Answer在这种情况下,外键字段, question的这种情况下,将“扩大”与QuestionSerializer等国外重点领域仍保持原点外键值, user在这种情况下,如果你的避风港没有在序列化程序中明确定义一个序列化程序字段。

Hope it would help. 希望这会有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM