gpt4 book ai didi

Django Rest Framework 使用 PrimaryKeyRelatedField 返回嵌套对象

转载 作者:行者123 更新时间:2023-12-04 18:43:07 26 4
gpt4 key购买 nike

我正在使用 DRF 来公开一些 API 端点。

# models.py

class Project(models.Model):
...
assigned_to = models.ManyToManyField(
User, default=None, blank=True, null=True
)



# serializers.py

class ProjectSerializer(serializers.ModelSerializer):
assigned_to = serializers.PrimaryKeyRelatedField(
queryset=User.objects.all(), required=False, many=True)

class Meta:
model = Project
fields = ('id', 'title', 'created_by', 'assigned_to')


# view.py

class ProjectList(generics.ListCreateAPIView):
mode = Project
serializer_class = ProjectSerializer
filter_fields = ('title',)

def post(self, request, format=None):
# get a list of user.id of assigned_to users
assigned_to = [x.get('id') for x in request.DATA.get('assigned_to')]
# create a new project serilaizer
serializer = ProjectSerializer(data={
"title": request.DATA.get('title'),
"created_by": request.user.pk,
"assigned_to": assigned_to,
})
if serializer.is_valid():
serializer.save()
else:
return Response(serializer.errors,
status=status.HTTP_400_BAD_REQUEST)
return Response(serializer.data, status=status.HTTP_201_CREATED)

这一切正常,我可以发布分配给字段的 id 列表。但是,要实现此功能,我必须使用 PrimaryKeyRelatedField而不是 RelatedField .这意味着当我做 GET那么我只在 assigned_to中收到用户的主键 field 。有什么方法可以维持 POST 的当前行为吗?但返回序列化的 User assigned_to 的详细信息 field ?

最佳答案

我最近用子类 PrimaryKeyRelatedField() 解决了这个问题它使用 id 作为输入来设置值,但使用序列化程序返回嵌套值。现在这可能不是这里要求的 100%。 POST、PUT 和 PATCH 响应也将包括嵌套表示,而问题确实指定 POST 的行为与它对 PrimaryKeyRelatedField 的行为完全相同。

https://gist.github.com/jmichalicek/f841110a9aa6dbb6f781

class PrimaryKeyInObjectOutRelatedField(PrimaryKeyRelatedField):
"""
Django Rest Framework RelatedField which takes the primary key as input to allow setting relations,
but takes an optional `output_serializer_class` parameter, which if specified, will be used to
serialize the data in responses.

Usage:
class MyModelSerializer(serializers.ModelSerializer):
related_model = PrimaryKeyInObjectOutRelatedField(
queryset=MyOtherModel.objects.all(), output_serializer_class=MyOtherModelSerializer)

class Meta:
model = MyModel
fields = ('related_model', 'id', 'foo', 'bar')

"""

def __init__(self, **kwargs):
self._output_serializer_class = kwargs.pop('output_serializer_class', None)
super(PrimaryKeyInObjectOutRelatedField, self).__init__(**kwargs)

def use_pk_only_optimization(self):
return not bool(self._output_serializer_class)

def to_representation(self, obj):
if self._output_serializer_class:
data = self._output_serializer_class(obj).data
else:
data = super(PrimaryKeyInObjectOutRelatedField, self).to_representation(obj)
return data

关于Django Rest Framework 使用 PrimaryKeyRelatedField 返回嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20181128/

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