gpt4 book ai didi

django - 我如何允许用户只修改他们在 django rest 框架中的数据?

转载 作者:行者123 更新时间:2023-12-05 08:00:36 25 4
gpt4 key购买 nike

我有一个只能由所有者修改的 Location 模型

class Location(models.Model):
user = models.ForeignKey(User)
name = models.CharField(max_length=100)
address = models.TextField()

这是 API Location Serializer

class LocationSerializer(serializers.ModelSerializer):

class Meta:
model = Location
fields = ('user', 'name', 'address',)

问题是我希望用户成为请求用户

实际上我覆盖了 View 集的创建方法,但我认为这不是最好的解决方案

class LocationViewSet(mixins.CreateModelMixin,
mixins.RetrieveModelMixin,
mixins.ListModelMixin,
GenericViewSet):
model = Location
serializer_class = LocationSerializer

def get_queryset(self):
return self.model.objects.filter(user=self.request.user)

def create(self, request, *args, **kwargs):
data = request.DATA.copy()
data.update({'user':unicode(self.request.user.id)})

serializer = self.get_serializer(data=data, files=request.FILES)

if serializer.is_valid():
self.pre_save(serializer.object)
self.object = serializer.save(force_insert=True)
self.post_save(self.object, created=True)
headers = self.get_success_headers(serializer.data)
return Response(serializer.data, status=status.HTTP_201_CREATED,
headers=headers)

return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

谢谢你的建议

最佳答案

您想调整 example from the tutorial about associating snippets with users .保留您的 get_queryset 实现,然后将 user 字段设置为 pre_save 中的请求用户。

关于django - 我如何允许用户只修改他们在 django rest 框架中的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17999481/

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