title: How do I solve django.db.utils.IntegrityError: UNIQUE constraint failed?
body: <p>How do I solve django.db.utils.IntegrityError: UNIQUE constraint failed?
  error code is
  django.db.utils.IntegrityError: UNIQUE constraint failed: Movies_comment.user_id, Movies_comment.tv_or_movie_id.</p>
  <p>This error occurs Comment(comment=form.cleaned_data[&quot;comment&quot;],user=request.user,stars=form.cleaned_data[&quot;stars&quot;],tv_or_movie=tv_or_movie_object).save()</p>
  <p>views.py</p>
  <pre><code>def view_tv_and_movie_detail(request, type_movie_or_tv, id):
      tv_or_movie_object, _ = TVAndMovie.objects.get_or_create(tmdb_id=id, judge_tv_or_movie=type_movie_or_tv)
      detail_tv_or_movie = TvAndMovieDetailhelp(request, tv_or_movie_object, 3)
      mycomment_obj = detail_tv_or_movie.get_user_post_comment_for_tv_or_movie()
      if request.method == &quot;POST&quot;:
          if request.POST.get(&quot;action&quot;) == &quot;delete&quot;:
              mycomment_obj.delete()
              return redirect(&quot;view_tv_and_movie_detail&quot;, type=type_movie_or_tv, id=id)
          else:
              form = CommentCreateForm(request.POST, instance=mycomment_obj)
              if form.is_valid() and request.POST.get(&quot;action&quot;) == &quot;update&quot;:
                  form.save()
                  return redirect(&quot;view_tv_and_movie_detail&quot;, type=type_movie_or_tv, id=id)
              elif form.is_valid() and request.POST.get(&quot;action&quot;) == &quot;create&quot;:
                  Comment(
                      comment=form.cleaned_data[&quot;comment&quot;],
                      user=request.user,
                      stars=form.cleaned_data[&quot;stars&quot;],
                      tv_or_movie=tv_or_movie_object,
                  ).save()
                  return redirect(&quot;view_tv_and_movie_detail&quot;, type=type_movie_or_tv, id=id)
      else:
          form = CommentCreateForm(instance=mycomment_obj)
      data = detail_tv_or_movie.get_object_tv_or_movie_data()
      recommendations = detail_tv_or_movie.get_recommendations_tmdb_data()
      pages = detail_tv_or_movie.get_page_comment()
      average = tv_or_movie_object.average_stars()
      context = {
          &quot;data&quot;: data,
          &quot;recommendations&quot;: recommendations,
          &quot;type&quot;: &quot;movie&quot;,
          &quot;mycomment&quot;: mycomment_obj,
          &quot;average&quot;: average,
          &quot;form&quot;: form,
          &quot;pages&quot;: pages
      }
      return render(request, &quot;Movie/movie_detail.html&quot;, context)
  </code></pre>
  <p>models.py</p>
  <pre><code>class TVAndMovie(models.Model):
      tmdb_id = models.CharField(
          validators=[alphanumeric], max_length=9999
      )
      judge_tv_or_movie = models.CharField(
          blank=False, null=False, default=&quot;movie&quot;, max_length=20
      )
      stars = models.FloatField(
          blank=False,
          null=False,
          default=0,
          validators=[MinValueValidator(0.0), MaxValueValidator(10.0)],
      )
  
      def get_judge_tv_or_movie(self) -&gt; str:
          return self.judge_tv_or_movie
  
      def get_comments(self) -&gt; object:
          return Comment.objects.prefetch_related(&quot;tv_or_movie&quot;).filter(
              tv_or_movie_id=self.id
          )
  
      def average_stars(self) -&gt; float:
          comments = self.get_comments()
          n_comments = comments.count()
  
          if n_comments:
              self.stars = round(
                  sum([comment.stars for comment in comments]) / n_comments, 3
              )
          else:
              self.stars = 0
          self.save()
          return self.stars
  
  
  class Comment(models.Model):
  
      comment = models.TextField(max_length=1000)
      stars = models.FloatField(
          blank=False,
          null=False,
          default=0,
          validators=[MinValueValidator(0.0), MaxValueValidator(10.0)],
      )
      user = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
      tv_or_movie = models.ForeignKey(TVAndMovie, on_delete=models.CASCADE)
      created_at = models.DateTimeField(auto_now_add=True)
      updated_at = models.DateTimeField(auto_now=True)
      
      class Meta:
          unique_together = (&quot;user&quot;, &quot;tv_or_movie&quot;)
          indexes = [models.Index(fields=[&quot;user&quot;, &quot;tv_or_movie&quot;])]
          
      def __str__(self) -&gt; str:
          return self.comment[:20]
  
  </code></pre>
  <p>helper_views.py</p>
  <pre><code>class TvAndMovieDetailhelp:
      def __init__(self, request, obj_tv_or_movie: object, page_num: int) -&gt; None:
          self.request = request
          self.obj_tv_or_movie: object = obj_tv_or_movie
          self.page_num: int = page_num
  
      def get_object_tv_or_movie_data(self) -&gt; dict:
          tv_or_movie_url: str = (
              &quot;https://api.themoviedb.org/3/&quot; +
              self.obj_tv_or_movie.judge_tv_or_movie +
              &quot;/&quot; +
              str(self.obj_tv_or_movie.tmdb_id) +
              &quot;?api_key=&quot; +
              TMDB_API_KEY +
              &quot;&amp;language=en-US&quot;
          )
          return (requests.get(tv_or_movie_url)).json()
  
      def get_recommendations_tmdb_data(self) -&gt; dict:
          recommendations_url: str = (
              &quot;https://api.themoviedb.org/3/&quot; +
              self.obj_tv_or_movie.judge_tv_or_movie +
              &quot;/&quot; +
              str(self.obj_tv_or_movie.tmdb_id) +
              &quot;/recommendations?api_key=&quot; +
              TMDB_API_KEY +
              &quot;&amp;language=en-US&quot;
          )
          return (requests.get(recommendations_url)).json()
  
      def get_comment_for_tv_or_movie(self) -&gt; object:
          if self.request.user.id is not None:
              return (
                  Comment.objects.filter(tv_or_movie=self.obj_tv_or_movie.id)
                  .exclude(user=self.request.user)
                  .order_by(&quot;-updated_at&quot;)
              )
          else:
              return Comment.objects.filter(tv_or_movie=self.obj_tv_or_movie.id).order_by(
                  &quot;-updated_at&quot;
              )
  
      def get_user_post_comment_for_tv_or_movie(self) -&gt; object:
          if self.request.user.id is not None:
              try:
                  return Comment.objects.get(
                      user=self.request.user, tv_or_movie=self.obj_tv_or_movie
                  )
              except Comment.DoesNotExist:
                  return None
          else:
              return None
  
      def get_page_comment(self):
          other_comments = self.get_comment_for_tv_or_movie()
          paginator = Paginator(other_comments, self.page_num)
          page = self.request.GET.get(&quot;page&quot;, 1)
          try:
              pages = paginator.page(page)
          except PageNotAnInteger:
              pages = paginator.page(1)
          except EmptyPage:
              pages = paginator.page(1)
          return pages
  
      def send_contexts_detail(self,form) -&gt; dict:
          data_for_tvor_movie = self.get_object_tv_or_movie_data()
          recommendations_data = self.get_recommendations_tmdb_data()
          for_movie_or_tv = self.obj_tv_or_movie.judge_tv_or_movie
          mycomment_obj = self.get_user_post_comment_for_tv_or_movie()
          average = self.obj_tv_or_movie.getaverage_stars()
          pages = self.get_page_comment()
          context = {
              &quot;data&quot;: data_for_tvor_movie,
              &quot;recommendations&quot;: recommendations_data,
              &quot;type&quot;: for_movie_or_tv,
              &quot;mycomment&quot;: mycomment_obj,
              &quot;average&quot;: average,
              &quot;form&quot;: form,
              &quot;pages&quot;: pages,  # NOTE add the comment to context
          }
          return context
  
  </code></pre>