我正在编写一个Django REST框架API。 我的模型有默认的Django PK供内部使用,uuid字段用于外部引用。在
class BaseModel(models.Model):
uuid = models.UUIDField(default=uuid.uuid4, editable=False)
class Event(BaseModel):
title = models.TextField()
location = models.ForeignKey('Location', null=True, on_delete=models.SET_NULL)
class Location(BaseModel):
latitude = models.FloatField()
longitude = models.FloatField()
我的序列化程序:
^{pr2}$这很好,这是我检索事件时得到的信息:
{
"uuid": "ef33db27-e98b-4c26-8817-9784dfd546c6",
"title": "UCI Worldcup #1 Salzburg",
"location": 1 # Note here I have the PK, not UUID
}
但我想要的是:
{
"uuid": "ef33db27-e98b-4c26-8817-9784dfd546c6",
"title": "UCI Worldcup #1 Salzburg",
"location": "2454abe7-7cde-4bcb-bf6d-aaff91c107bf" # I want UUID here
}
当然,我希望这种行为对我所有的外国公司和许多领域都有效。 有没有办法为嵌套模型定制DRF使用的字段? 谢谢!在
对于嵌套模型字段,您可以在如下序列化程序中使用
source
参数我的一个朋友给我寄来这个解决方案: 它适用于我所有的相关对象。在
相关问题 更多 >
编程相关推荐