django rest保存时将数据添加到序列化程序

时间:2017-02-20 13:44:46

标签: django serialization django-rest-framework

我想做以下事情:

models.py

class MyModel(TimeStampedModel, models.Model):
    name = models.CharField(max_length=100)
    owner = models.ForeignKey(settings.AUTH_USER_MODEL)

serializers.py

class MyModelSerializerCreate(serializers.ModelSerializer):

    class Meta:
        model = MyModel
        fields = (
            'name',
        )

我想在request.user中添加当前用户的所有者。 目前我在我的视图中通过向用户提升request.data直接添加它,然后将更新的数据传递给我的序列化器。

    data = request.data
    # Add owner to data
    data["owner"] = request.user.pk
    serializer = self.get_serializer(data=data)
    serializer.is_valid(raise_exception=True)
    self.perform_create(serializer)
    headers = self.get_success_headers(serializer.data)

我想直接在我的序列化程序中执行此操作,但无法找到正确执行此操作的方法,因为它看起来像是对我进行数据验证。这是一个好主意吗 ?我应该将这个逻辑保留在我的视图中还是将其移动到我的序列化程序中?

3 个答案:

答案 0 :(得分:10)

您可以从序列化程序上下文中获取用户:

self.context['request'].user
它来自最初在get_serializer_context

中创建的方法GenericAPIView
class GenericAPIView(APIView):
    ....
    def get_serializer_context(self):
        """
        Extra context provided to the serializer class.
        """
        return {
            'request': self.request,
            'format': self.format_kwarg,
            'view': self
        }  

在序列化程序中,您需要覆盖create方法:

class MyModelSerializerCreate(serializers.ModelSerializer):

    class Meta:
        model = MyModel
        fields = ('name', )

    def create(self, validated_data):
        validated_data['owner'] = self.context['request'].user
        return super(MyModelSerializerCreate, self).create(validated_data)

如果您需要与update模型进行一些特殊互动,也可以覆盖deleteuser方法。

答案 1 :(得分:1)

不幸的是,我没有名声点对上面的@ ivan-Semochkin帖子发表评论,但最后一行不应该是:

#include <iostream>    

using namespace std;

struct Node {
    int data;
    Node* next;
};

void add(struct Node *head, int n) {
    Node *newNode = new Node;
    newNode->data = n;
    newNode->next = NULL;
    Node *cur = head;
    while(cur) {
        if(cur->next == NULL) {
            cur->next = newNode;
            return;
        }

        cur = cur->next;
    }
}

void display(struct Node *head) {
    Node *list = head;
    while(list) {
        cout << list->data << " ";
        list = list->next;
    }
    cout << endl;
    cout << endl;
}

int main()
{
    struct Node *newHead;
    struct Node *head = new Node;
    int ar[]={2,5,46,7,55};
    for(int i=0; i<5;i++){
        add(head,ar[i]);
    }
    display(head);
}

答案 2 :(得分:0)

Ivan Semochkin的解决方案对我不起作用,因为它从未进入序列化程序的create()方法中。由于request.data字段是不可变的,因此您需要将其复制然后扩展。

from django.http import HttpRequest
from rest_framework.request import Request

class MyModelViewSet(ModelViewSet):
    def _extend_request(self, request):
        data = request.POST.copy()
        data['owner'] = request.user
        request_extended = Request(HttpRequest())
        request_extended._full_data = data

    def create(self, request, *args, **kwargs):
        request_extended = self._extend_request(request)
        return super().create(request_extended, *args, **kwargs)