现有客户端已在以类似以下结构发送数据……
{
"hive_metadata": {"name": "hive name"},
"bees": [{"name": "bee 1", "name": "bee 2", ...}]
}
对于如下模型:
class Hive(models.Model):
name = models.CharField(max_length=32, help_text="name")
class Bee(models.Model):
name = models.CharField(max_length=32, help_text="name")
hive = models.ForeignKey(
Hive, help_text="The Hive associated with this Bee", on_delete=models.CASCADE
)
实现这一点的代码会手动迭代传入的数据。我想使用 django rest 框架序列化程序重写它;但是,hive_metadata
嵌套本身这一事实到目前为止让我很困惑。
如果我写
class BeesSerializer(ModelSerializer):
class Meta:
model = models.Bee
fields = ("name",)
class PopulatedHiveSerializer(ModelSerializer):
bees = BeesSerializer(many=True, source="bee_set")
class Meta:
model = models.Hive
fields = ("name","bees",)
会产生
{
"name": "hive name",
"bees": [{"name": "bee 1", "name": "bee 2", ...}]
}
很容易。我曾希望通过引用子序列化器来解决这个问题,比如
class HiveMetaDataSerializer(ModelSerializer):
class Meta:
model = models.Hive
fields = ("name",)
class PopulatedHiveSerializer(ModelSerializer):
bees = BeesSerializer(many=True, source="bee_set")
hive_metadata = HiveMetaDataSerializer(source=???)
class Meta:
model = models.Hive
fields = ("hive_metadata","bees",)
但我似乎无法弄清楚在“源”中放什么,以便相同的对象通过外部序列化器传递到内部。
那么,有没有办法使用 django rest 框架序列化器来做到这一点?