gpt4 book ai didi

python - Django Rest Framework 在 POST 中接收主键值并将模型对象作为嵌套序列化程序返回

转载 作者:行者123 更新时间:2023-12-04 13:02:37 28 4
gpt4 key购买 nike

我不完全确定我的问题的标题是否像我希望的那样具体,但情况是这样:

我有一个 HyperlinkedModelSerializer看起来像这样:

class ParentArrivalSerializer(serializers.HyperlinkedModelSerializer):
carpool = SchoolBuildingCarpoolSerializer()

class Meta:
model = ParentArrival

如您所见 carpool被定义为嵌套的序列化程序对象,我想要的是能够发出 POST 请求来创建 ParentArrival以这种方式(数据为应用程序/json):
{
...
"carpool": "http://localhost:8000/api/school-building-carpools/10/"
...
}

并以这种方式接收数据:
{
"carpool": {
"url": "http://localhost:8000/api/school-building-carpools/10/"
"name": "Name of the carpool",
...
}
}

基本上,我正在寻找一种处理嵌套序列化程序的方法,而不必在 POST 请求中将数据作为对象(但在本例中为 id 或 url)发送,但接收嵌套在序列化响应中的对象。

最佳答案

我对我以前的解决方案很满意,但决定再看一遍,我想我有另一个解决方案可以完全满足您的需求。

基本上,您需要创建自己的自定义字段,只需覆盖 to_representation方法:

class CarpoolField(serializers.PrimaryKeyRelatedField):
def to_representation(self, value):
pk = super(CarpoolField, self).to_representation(value)
try:
item = ParentArrival.objects.get(pk=pk)
serializer = CarpoolSerializer(item)
return serializer.data
except ParentArrival.DoesNotExist:
return None

def get_choices(self, cutoff=None):
queryset = self.get_queryset()
if queryset is None:
return {}

return OrderedDict([(item.id, str(item)) for item in queryset])

class ParentArrivalSerializer(serializers.HyperlinkedModelSerializer):
carpool = CarpoolField(queryset=Carpool.objects.all())

class Meta:
model = ParentArrival

这将允许您发布
{
"carpool": 10
}

并得到:
{
"carpool": {
"url": "http://localhost:8000/api/school-building-carpools/10/"
"name": "Name of the carpool",
...
}
}

关于python - Django Rest Framework 在 POST 中接收主键值并将模型对象作为嵌套序列化程序返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36189303/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com