IntegrityError IntegrityError位于/ api / movies / 2 / rate_movie

时间:2020-08-02 05:50:37

标签: python django

我从邮递员api发送数据时说

/ api / movies / 2 / rate_movie /中的IntegrityError 唯一约束失败:api_rating.user_id,api_rating.movi​​e_id

我尝试过

Rating.objects.update_or_create(user = user,movie = movie,defaults = {stars:stars})

在视图中也是如此,但是在尝试了此数据之后,但是它不会更新数据

这是我的views.py

from django.shortcuts import render
from rest_framework import viewsets, status
from rest_framework.response import Response
from .models import Movie, Rating
from .serializers import MovieSerializer, RatingSerializer 
from rest_framework.decorators import action
from django.contrib.auth.models import User
# Create your views here.
class MovieViewSet(viewsets.ModelViewSet):
    queryset = Movie.objects.all()
    serializer_class = MovieSerializer

    @action(detail=True, methods=['POST'])
    def rate_movie(self, request, pk=None):
        if 'stars' in request.data:
            movie = Movie.objects.get(id=pk)
            stars = request.data['stars']
            #user = request.user
            user = User.objects.get(id=1)
            print('user',user)
            print('movie title', movie.title)
            try:
                rating = Rating.object.get(user=user.id, movie=movie.id)
                rating.stars = stars
                rating.save()
            except:
                Rating.objects.update_or_create(user=user, movie=movie, stars=stars)


            response = {'message':'its working'}
            return Response(response, status=status.HTTP_200_OK)
        else:
            response = {'message':'you need to provide stars'}
            return Response(response, status=status.HTTP_400_BAD_REQUEST)


class RatingViewSet(viewsets.ModelViewSet):
    queryset = Rating.objects.all()
    serializer_class = RatingSerializer
    

这是我的模型。py

from django.db import models
from django.contrib.auth.models import User
from django.core.validators import MaxValueValidator, MinValueValidator
# Create your models here.

class Movie(models.Model):
    title = models.CharField(max_length=32)
    description = models.TextField(max_length=360)

class Rating(models.Model):
    movie = models.ForeignKey(Movie, on_delete=models.CASCADE)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    stars = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(5)], null=True)
    
    class Meta:
        unique_together = (('user','movie'),)
        index_together = (('user','movie',),)

1 个答案:

答案 0 :(得分:0)

我认为您正在尝试保存评分时出现问题。我已经更新了该部分-首先过滤以获取正确的条目,然后获取评分,然后以星号更新条目。

@action(detail=True, methods=['POST'])
def rate_movie(self, request, pk=None):
    if 'stars' in request.data:
        movie = Movie.objects.get(id=pk)
        stars = request.data['stars']
        #user = request.user
        user = User.objects.get(id=1)
        print('user',user)
        print('movie title', movie.title)
        rating = Rating.object.filter(user=user.id, movie=movie.id)
        rating.stars = stars
        rating.update(stars = stars)