gpt4 book ai didi

python - django-rest-framework 反序列化请求以创建具有用户外键的对象

转载 作者:太空宇宙 更新时间:2023-11-04 03:19:31 26 4
gpt4 key购买 nike

我想创建一个带有外键 request.userSpiderService

模型:

from django.contrib.auth.models import User

class SpiderService(models.Model):
user = models.ForeignKey(User)
name = models.CharField(max_length=20)

序列化器:

class SpiderServiceSerializer(serializers.ModelSerializer):
user = serializers.ReadOnlyField(source='user.id')

class Meta:
model = SpiderService
fields = ('id', 'user', 'name')

class SpiderServiceListSerializer(viewsets.ModelViewSet):
queryset = SpiderService.objects.all()
serializer_class = SpiderService

观看次数:

class SpiderServiceList(APIView):

def get(self, request, format=None):
services = SpiderService.objects.all()
serializer = SpiderServiceSerializer(services, many=True)
return Response(serializer.data)

def post(self, request, format=None):
serializer = SpiderServiceSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

def perform_create(elf, serializer):
serializer.save(user=self.request.user)

当我发帖时

{
"name": "2"
}

到 api url,出现 500 错误:

[01/Feb/2016 15:39:55] "POST /services/ HTTP/1.1" 500 17105
IntegrityError: NOT NULL constraint failed: spmanage_spiderservice.user_id

我已阅读 Serializer relations发现我不应该像上面那样写代码。官方的例子相当于去掉了SpiderServiceSerializer中的user field,在UserSerializer中增加了一个spiderservice field。貌似目标是在 django 模型中实现类似 user.spiderservice_set 的语法,这不符合我的目的。

我只想用 request.user 创建一个 spiderservice 对象。

如何解决?

最佳答案

您需要将当前用户添加为 extra parameter to the Serializer's save method :

serializer.save(user=request.user)

关于python - django-rest-framework 反序列化请求以创建具有用户外键的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35125763/

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