创建时将额外字段添加到Django-rest-framework ModelViewSet的最佳方法 [英] best way to add additional fields to django-rest-framework ModelViewSet when create

查看:137
本文介绍了创建时将额外字段添加到Django-rest-framework ModelViewSet的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Book模型,该模型带有一个用户(书的所有者)外键:

I have a Book model with a foreign key to user (the owner of the book):

class Book(models.Model):
    owner = models.ForiegnKey(User)
    ...

我为Book创建了一个ModelViewSet,它显示了登录用户拥有的书:

I've created a ModelViewSet for Book which shows the books owned by the logged in user:

class BookViewSet(viewsets.ModelViewSet):
    model = Book
    serializer_class = BookSerializer
    def get_queryset(self):
        return Book.objects.filter(owner=self.request.user)

现在要创建一本新书,我想用request.user保存用户字段,而不要保存其余部分发送的数据客户端(以提高安全性)。例如:

Now to create a new book, I want to save user field with request.user, not with data sent from the rest client (for more security). for example:

def create(self, request, *args, **kwargs):
    request.DATA['user'] = request.user
    ... (some code to create new Book from request.DATA using serialize class)

,但出现此错误:
此QueryDict实例是不可变的。 (意味着request.DATA是一个不变的QueryDict,不能更改)

but I got this error: This QueryDict instance is immutable. (means request.DATA is a immutable QueryDict and can't be changed)

您知道在使用django rest框架创建对象时添加其他字段的更好方法吗?

Do you know any better way to add additional fields when creating an object with django rest framework?

推荐答案

更新:自v3起,您需要执行以下操作:

Update: Since v3 you need to do this:

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

原理保持不变。

您希望将图书序列化器的 owner 字段设为只读,然后在 pre_save()

You want to make the owner field of your book serializer read-only and then set the association with the user in pre_save().

类似的东西:

def pre_save(self, obj):
    obj.owner = self.request.user

请参见有关关联代码段的教程部分与用户打交道。

See the tutorial section on "Associating Snippets with Users".

我希望对您有所帮助。

这篇关于创建时将额外字段添加到Django-rest-framework ModelViewSet的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆