如何通过Post JSON使用CreateAPIView创建模型实例

时间:2019-04-18 10:27:18

标签: django django-rest-framework

我与用户建立了StudyGroup模型。如果我想使用CreateAPIView来创建StudyGroup,我必须发布哪些数据来创建StudyGroup模型?

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

class StudyGroup(models.Model):
    class Meta:
        ordering = ('created',)
    created = models.DateTimeField(auto_now_add=True)
    name = models.CharField(max_length=20)
    users = models.ManyToManyField(User, related_name='study_groups')

from rest_framework import serializers

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'username', 'study_groups')

class StudyGroupSerializer(serializers.ModelSerializer):
    users = UserSerializer(many=True)
    class Meta:
        model = StudyGroup
        fields = ('id', 'name', 'users')

from rest_framework import generics, permissions
from django.contrib.auth.models import User

class StudyGroupCreate(generics.CreateAPIView):
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
    queryset = StudyGroup.objects.all()
    serializer_class = StudyGroupSerializer


urlpatterns = [
    path('create_study_group/', views.StudyGroupCreate.as_view()),
]

已发布的数据(“名称”:“ created_group”在正文中,并且auth可以)

"users": [2, 3]     // 2, 3 is userid in DB
"users": 2

"users": ["A", "B"] // A, B is username in DB
"users": "A"

响应状态= 400

{
    "users": [
        "This field is required."
    ]
}

1 个答案:

答案 0 :(得分:0)

研究组序列化程序中有users = UserSerializer(many=True)表示它期望使用用户序列化程序中定义的一组用户对象。要发布用户,建议在序列化器中添加仅写的另一字段,而您定义的字段应为只读。像这样:

class StudyGroupSerializer(serializers.ModelSerializer):
    users = UserSerializer(many=True, read_only=True)
    user_ids = serializers.PrimaryKeyRelatedField(many=True, queryset=User.objects.all(), required=True, write_only=True)
    # these ids get converted to actual users after validation
    class Meta:
        model = StudyGroup
        fields = ('id', 'name', 'users', 'user_ids')

    def create(self, validated_data):
        user_ids = validated_data.pop('user_ids')
        instance = super().create(validated_data)
        for user in user_ids:
            instance.users.add(user)
        return instance