django APIView发布函数未添加到数据库

1bqhqjot  于 2022-12-20  发布在  Go
关注(0)|答案(3)|浏览(96)

我有以下模型:

class Follow(models.Model):
    user = models.ForeignKey(
        "User", related_name="follower", on_delete=models.CASCADE)
    following_user = models.ForeignKey(
        "User", related_name="following", blank=True, on_delete=models.CASCADE)
    date_followed = models.DateTimeField(editable=False, default=timezone.now)

    class Meta:
        constraints = [
            models.UniqueConstraint(
                fields=['user', 'following_user'],  name="unique_followers")
        ]

        ordering = ["-date_followed"]

    def __str__(self):
        return f"{self.user.username} follows {self.following_user.username}"

和串行器:

class FollowSerializer(serializers.ModelSerializer):

    class Meta:
        model = Follow
        fields = ['user', 'following_user', 'date_followed']

然后在我的视图中,我有一个APIView创建以下内容:

class FollowingView(APIView):
    permission_class = [permissions.IsAuthenticated]
    queryset = Follow.objects.all()
    serializer_class = FollowSerializer

    def post(self, request):
        user = request.data.get('user')
        following_user = request.data.get('to_user')

        try:
            follow = Follow.objects.create(
                user=user, following_user=following_user)
            follow.save()

            serializer = FollowSerializer(follow)

            print(serializer.data)

            def __str__(self):
                return f"{self.request.username} follows {self.following_user_id.username}"

            return Response(serializer.data, status=status.HTTP_201_CREATED)
        except:
            return Response(status=status.HTTP_400_BAD_REQUEST)

不知道出了什么问题。我可以打印参数,但似乎创建功能没有通过。
感谢您的帮助!

7gyucuyw

7gyucuyw1#

第一个问题是在这一行:

following_user = request.data.get('to_user')

序列化程序中没有这样的to_user字段,因此从请求中获取的值是None。请相应地替换该变量。

following_user = request.data.get('following_user')

其次,我们尝试直接使用ID而不是用户示例创建Follow对象,在尝试创建对象之前,只需获取用户示例。

from rest_framework import permissions
from core.models import Follow
from core.api.serializers import FollowSerializer
from django.contrib.auth import get_user_model

class FollowingView(APIView):
    permission_class = [permissions.IsAuthenticated]
    queryset = Follow.objects.all()
    serializer_class = FollowSerializer

    def post(self, request):
        user_id = request.data.get('user')
        following_user_id = request.data.get('following_user')

        user = get_object_or_404(get_user_model(), id=user_id)
        following_user = get_object_or_404(get_user_model(), id=following_user_id)

        try:
            follow = Follow.objects.create(
            user=user, following_user=following_user)
            follow.save()
            serializer = FollowSerializer(follow)
            print(serializer.data)

            def __str__(self):
                return f"{self.request.username} follows {self.following_user_id.username}"

            return Response(serializer.data, status=status.HTTP_201_CREATED)
        except:
            return Response(status=status.HTTP_400_BAD_REQUEST)

编辑:有关如何正确使用序列化程序验证数据,请参阅@Ankit Tiwari的回答

ghhaqwfi

ghhaqwfi2#

如果不从客户端获取数据,请首先将 read_only=True 设置为user&following_user字段。

class FollowSerializer(serializers.ModelSerializer):
    user = serializers.PrimaryKeyRelatedField(many=False, read_only=True)
    following_user = serializers.PrimaryKeyRelatedField(many=False, read_only=True)
    class Meta:
        model = Follow
        fields = ['user', 'following_user', 'date_followed']

在视图中,只需验证序列化程序并将其与相关字段一起保存

class FollowingView(APIView):
    permission_class = [permissions.IsAuthenticated]
    queryset = Follow.objects.all()
    serializer_class = FollowSerializer

    def post(self, request):
        user = request.data.get('user')
        following_user = request.data.get('to_user') # check if it's correct

        try:
            user = User.objects.get(id=user)
            following_user = User.objects.get(id=following_user)
            serializer = FollowSerializer(request.data)
            if serializer.is_valid():
               serializer.save(
                 user=user,
                 following_user=following_user
               )

            def __str__(self):
                return f"{self.request.username} follows {self.following_user_id.username}"

            return Response(serializer.data, status=status.HTTP_201_CREATED)
        except:
            return Response(status=status.HTTP_400_BAD_REQUEST)
ehxuflar

ehxuflar3#

您需要删除与object.create一起使用的.save()方法。
object.create用于保存表中的数据对象,因此无需.save()

follow = Follow.objects.create(user=user, following_user=following_user)
serializer = FollowSerializer(follow)
print(serializer.data)

您还可以保存数据并使用APIView()方法对其进行序列化,如下所示

def post(self, request):
    serializer = FollowSerializer(data=request.data)
    print(serializer.is_valid()) ## for debug
    print(serializer.errors) ## for debug
    if serializer.is_valid():
        serializer.save()
        return Response({'msg':'Data Created'}, status=status.HTTP_201_CREATED)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

相关问题