когда я отправляю данные из api почтальона, он говорит:
IntegrityError в / api / movies / 2 / rate_movie / UNIQUE ограничение не удалось: api_rating.user_id, api_rating.movie_id
я попробовал
Rating.objects.update_or_create (user = user, movie = mov ie, 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
и вот мой models.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',),)