在更新时创建只读字段,但不在ModelSerializer的CREATE方法中创建

时间:2018-09-20 04:34:28

标签: python django django-rest-framework

在python中是一个新手,我想在Django中创建一个API,这是面临的挑战之一,它正在尝试使UPDATE端点和CREATE端点正常工作。

当我在UPDATING期间忽略某些必填字段时,它可以工作,但是对于CREATE方法却不起作用,它会显示以下错误消息:

IntegrityError at /api/articles/comment/4/replies/ null value in column "author_id" violates not-null constraint DETAIL: Failing row contains (2018-09-20 04:24:36.225977+00, 89, English is better, null, null)

当我在序列化程序中删除read_only时,问题出在 postman 中的UPDATE端点上:

{
    "comment": [
        "This field is required."
    ],
    "author": [
        "This field is required."
    ]
}

以下是我的代码段:

我在serializers.py中的序列化器

class RepliesSerializer(serializers.ModelSerializer):


    class Meta:
        model = Replies
        fields = '__all__'
        read_only_fields = ('comment', 'author',)

views.py中的视图。

class RepliesView(APIView):
    permission_classes = (IsAuthenticated,)

    def get_object(self, pk):
        try:
            return Replies.objects.get(pk=pk)
        except Replies.DoesNotExist:
            raise Http404

    def post(self, request, commentID):

        content = request.data
        author = request.user.id

        content['author'] = author
        content['comment'] = commentID
        # print('--> ', author)
        # print('content ---> ',content)
        serializer = RepliesSerializer(data=content)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def get(self,request, commentID):
        instance = Replies.objects.all()
        serializer = RepliesSerializer(instance, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)

    def delete(self, request, Id, format=None):
        snippet = self.get_object(Id)
        snippet.delete()
        return Response({"message" : "Reply Deleted Successfully."}, status=status.HTTP_204_NO_CONTENT)


    def put(self, request, Id):

        content = self.get_object(Id)
        serializer = RepliesSerializer(content, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

model.py中的模型类

"""
class to declare an article
model. To be used for all articles
"""

from django.db import models
from django.utils import timezone

from authors.apps.articles.utils import generate_slug
from authors.apps.authentication.models import User


# noinspection SpellCheckingInspection
class Article(models.Model):
    """
    A model for an article
    """
    slug = models.SlugField(max_length=100, unique=True)

    author = models.ForeignKey(User, on_delete=models.CASCADE)

    title = models.CharField(max_length=255, null=False, blank=False,
                             error_messages={"required": "Write a short title for your article."})

    description = models.TextField(null=False, blank=False,
                                   error_messages={"required": "A description of your post is required."})

    body = models.TextField(null=False, blank=False,
                            error_messages={"required": "You cannot submit an article without body."})

    created_at = models.DateTimeField(auto_created=True, auto_now=False, default=timezone.now)

    updated_at = models.DateTimeField(auto_created=True, auto_now=False, default=timezone.now)

    favorited = models.BooleanField(default=False)

    favorites_count = models.IntegerField(default=0)

    photo_url = models.CharField(max_length=255, null=True)

    def __str__(self):

        """
        :return: string
        """
        return self.title

    def save(self, *args, **kwargs):
        """
        override default save() to generate slug
        :param args:
        :param kwargs:
        """
        self.slug = generate_slug(Article, self)

        super(Article, self).save(*args, **kwargs)

    class Meta:
        get_latest_by = 'created_at'
        ordering = ['-created_at', 'author']


class Comments(models.Model):

    article = models.ForeignKey(Article, related_name='comments', on_delete=models.CASCADE)

    author = models.ForeignKey(User, on_delete=models.CASCADE)

    body = models.TextField(null=False, blank=False, error_messages={"required": "You cannot submit without a comment."})

    created_at = models.DateTimeField(auto_created=True, auto_now=False, default=timezone.now)

    def __str__(self):
        """
        :return: string
        """
        return self.body

    class Meta:
        get_latest_by = 'created_at'
        ordering = ['-created_at']


class Replies(models.Model):

    comment = models.ForeignKey(Comments, related_name='replies', on_delete=models.CASCADE)

    author = models.ForeignKey(User, related_name='replies',  on_delete=models.CASCADE)

    content = models.TextField(null=False, blank=False,
                            error_messages={"required": "You cannot submit without a reply."})

    created_at = models.DateTimeField(auto_created=True, auto_now=False, default=timezone.now)

    def __str__(self):
        """
        :return: string
        """
        return self.content

    class Meta:
        get_latest_by = 'created_at'
        ordering = ['-created_at']

我该如何确定同时针对UPDATING和CREATING的逻辑以避免这种错误。

1 个答案:

答案 0 :(得分:1)

将字段设置为只读不能解决您的问题。即使默认情况下将其设置为read_only,模型也无法在数据库中存储空白值。如果在创建对象时未创建作者和注释,则以允许空白和空值的方式修改模型。

author = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True)