【问题标题】:How to create new instances of both models contributing in OneToOne relationship in django rest framework (DRF)?如何在 django rest 框架(DRF)中创建有助于 OneToOne 关系的两个模型的新实例?
【发布时间】:2021-03-17 04:47:13
【问题描述】:

我创建了一个 Author 模型,其中它与默认 Django 用户具有 OneToOne 关系,如下所示:

from django.contrib.auth.models import User
from django.db import models


class Author(models.Model):
    user = models.OneToOneField(
        User,
        related_name='author',
        on_delete=models.CASCADE,
        default="",
    )

    is_author = models.BooleanField(
        default=True
    )

在这里我创建了以下视图集:

class AuthorViewSet(viewsets.ModelViewSet):
    serializer_class = AuthorSerializer
    queryset = Author.objects.all()

    def get_permissions(self):
        if self.action == "list" or self.action == "retrieve" or self.action == "update":
            self.permission_classes = [IsCurrentOwner, permissions.IsAdminUser]

        elif self.action == "create":
            self.permission_classes = [permissions.AllowAny]

        return super(AuthorViewSet, self).get_permissions()

问题 有什么方法可以一步创建userauthor(请求)?怎么样?

序列化代码:

class AuthorSerializer(serializers.ModelSerializer):

    class Meta:
        model = Author
        fields = "__all__"

        extra_kwargs = {
            'password': {'write_only': True},
            'id': {'read_only': True}
        }

我已经尝试了以下请求,但它不起作用。

#url: localhost:8000/users/
#method: POST

{
    "user": {
        "username": "mostafa",
        "password": "1"
    }       
}

错误:

{
    "user": [
        "Incorrect type. Expected pk value, received dict."
    ]
}

【问题讨论】:

    标签: python django django-rest-framework


    【解决方案1】:

    为此,您需要为用户创建另一个序列化程序:

    class UserSerializer(serializers.ModelSerializer):
        class Meta:
            model = User
            fields = "__all__"
    
            extra_kwargs = {
                'password': {'write_only': True},
            }
    

    之后,将AuthorSerializer 中的用户字段设为UserSerializer 的实例,并以这种方式覆盖create 方法:

    class AuthorSerializer(serializers.ModelSerializer):
        user = UserSerializer()
        
        class Meta:
            model = Author
            fields = "__all__"
    
            extra_kwargs = {
                'id': {'read_only': True}
            }
    
        def create(self, validated_data):
            user = None
            if "user" in validated_data:
                user_data = validated_data.pop("user") or {}
                user = User.objects.create_user(**user_data) # Assuming that it is default django user model
            author = Author.objects.create(user=user, **validated_data)
            author.save()
            return author
    

    请求负载的卷曲脚本:

    curl --location --request POST 'http://127.0.0.1:8000/users/' \
    --header 'Content-Type: application/json' \
    --data-raw '{
        "user": {
            "username": "mostafa",
            "password": "abcd"
        },
        "is_author": true
    }'
    

    它的响应如下:

    {
        "id": 1,
        "user": {
            "id": 1,
            "last_login": null,
            "is_superuser": false,
            "username": "mostafa",
            "first_name": "",
            "last_name": "",
            "email": "",
            "is_staff": false,
            "is_active": true,
            "date_joined": "2020-12-05T09:54:37.674749Z",
            "groups": [],
            "user_permissions": []
        },
        "is_author": true
    }
    

    【讨论】:

    • 能否添加示例请求以创建新用户和作者?
    • 这里的创建用户只是一个虚拟部分。我不确定您是否使用默认用户模型。如果您使用的是默认模型,那么我将在此处更新答案。
    • 你对this problem有什么想法吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-06
    • 2021-07-13
    • 2011-01-16
    • 1970-01-01
    • 2011-08-02
    相关资源
    最近更新 更多