我正在尝试按照本文档创建嵌套的序列化程序和api视图。 https://www.django-rest-framework.org/api-guide/relations/#nested-relationships
但是,由于无法预期我的结果,我无法理解我错过了什么。
我按照这个例子进行了研究,并检查了其他有关该例子的指南。尝试了不同的视图和不同的序列化器格式。
模型代码是这样的:-
class Round(models.Model):
player_num = models.IntegerField(null=False, default=1)
class Seats(models.Model):
stack = models.IntegerField(null=False, default=0)
round = models.ForeignKey(Round, on_delete=models.CASCADE)
state = models.IntegerField(choices=STATE)
序列化器的代码是这样的:-
class SeatsSerializer(serializers.ModelSerializer):
class Meta:
model = Seats
fields = ('stack','state')
class RoundSerializer(serializers.ModelSerializer):
seats = SeatsSerializer(many = True, read_only=True)
class Meta:
model = Round
fields = ('player_num','seats')
我想要这样的输出:
{
'player_num': 3,
'seats': [
{'stack': 100, 'state': 'participating', 'name': 'p1', 'uuid': 'ftwdqkystzsqwjrzvludgi'},
{'stack': 100, 'state': 'participating', 'name': 'p2', 'uuid': 'bbiuvgalrglojvmgggydyt'},
]
}
但是,我得到的输出是:
{
'player_num': 3,
}
答案 0 :(得分:2)
尝试一下:
round = models.ForeignKey(Round, on_delete=models.CASCADE, related_name='seats')