[Fixed]-DRF PUT request on unique model field

1👍

The problem is in Movie model defined by you.
When you set the name field of Movie model as unique = True,then any new entry with same movie name will always throw an error.

In your model,

class Movie(models.Model):
    name = models.CharField(max_length=800, unique=True)
    imdb_rating = models.IntegerField(null=True)
    movie_choice = (
        ('Act', 'Action'),
      ...........
    )
    movie_type = models.CharField(max_length=3, choices=movie_choice)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

If you want to add two entries with the same name,remove the line unique = True or make sure to save every entry with a different name.

Or,if you want to update the record/entry then you don’t need to assign a value for name field,just remove that line from your code,alternatively check if the name of the movie is already same with an improvement in the code like this :

class HirenSerializer(serializers.ModelSerializer):
    movie = MovieSerializer()

    class Meta:
        model = Hiren
        fields = ('movie', 'id', 'watched_full', 'rating', 'source', 'video_quality', 'watched_at')

    def update(self, instance, validated_data):
        movie_name = validated_data.get('movie', {}).get('name')

        if  movie_name != instance.movie.name :
            instance.movie.name = movie_name

        instance.movie.imdb_rating = validated_data.get('movie', {}).get('imdb_rating')
        instance.movie.movie_type = validated_data.get('movie', {}).get('movie_type')
        instance.watched_full = validated_data.get('watched_full', instance.watched_full)
        instance.rating = validated_data.get('rating', instance.rating)
        instance.source = validated_data.get('source', instance.source)
        instance.video_quality = validated_data.get('video_quality', instance.video_quality)
        instance.watched_at = validated_data.get('watched_at', instance.watched_at)
        instance.save()

        return instance

Hope this helps,Thanks.

Leave a comment