嵌套的序列化程序显示空数据
from rest_framework import serializers
from .models import PlayerTable, ChildTable
class ChildTableSerializer(serializers.ModelSerializer):
# x= ChildTable.objects.all().values
class Meta:
model = ChildTable
fields = ('season','goals','fk')
# fields =('fk',)
class PlayerTableSerializer(serializers.ModelSerializer):
player_details = ChildTableSerializer(many=True, read_only=True)
class Meta:
model = PlayerTable
fields = ('player_details',)
请帮助序列化程序获取的数据为空
答案 0 :(得分:0)
'player-details'
字段是什么?这不是您的PlayerTable
模型上的字段。您需要使用相关字段的名称。在您的情况下,由于您具有ForeignKey
关系ChildTable
-->
PlayerTable
,而您没有指定related_name
,因此它是childtable_set
。因此,如果您这样做,它应该可以工作:
class PlayerTableSerializer(serializers.ModelSerializer):
childtable_set = ChildTableSerializer(many=True, read_only=True)
class Meta:
model = PlayerTable
fields = ('childtable_set',)
或者,更改模型命名以更符合Django约定:
class PlayerDetail(models.Model):
player = models.ForeignKey(Player, db_column="fk", related_name="player_details", null=True, blank=True, on_delete=models.CASCADE)
...
class Meta:
managed = False
db_table = "child_table"
class Player(models.Model):
name = models.CharField(db_column="player_name", ...)
class Meta:
db_table = "player_table"
然后您的序列化程序将起作用,因为该关系为player_details
。这还有一个优势,当您执行details.player
时,您获得了播放器对象(现在,您必须执行details.fk
,但实际上并没有返回外键值,而是返回了{{1} }对象)。此外,您的模型还具有更多的pythonic名称(Player
而非Player
)。您的代码将更具可读性。