Instead of Primary Key Send Different Field in Django REST Framework

前端 未结 5 1050
萌比男神i
萌比男神i 2020-12-30 07:27

serializers.py

class MovieSerializer(serializers.ModelSerializer):

    class Meta:
        model = Movie
        fields = [
            \'popular         


        
5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-30 07:49

    The easy solution would be to change the Genre model to use name as primary key, like so:

    class Genre(models.Model):
        name = models.CharField(max_length=30, primary_key=True)
    

    Not that it matters much here, but this will also save a column in the database, since the auto generated id column will disappear :)


    Update

    After some discussion in the comments to this answer, I find it important to mentions that using ANY type as primary key, you should also avoid changing that field afterwards.

    This is because a change to the primary key, also necessitates an update to all the foreign keys pointing to that primary key, and (to put it in terms of this question) even though your table with genres may be relatively small, you may have a significant amount of movies pointing to each genre.

提交回复
热议问题