Skip to content Skip to sidebar Skip to footer

Cannot Post Entry Specifying Specific Id If The Id Is Specified As Foreignkey In Django

I have two models, Book and ReadBy as specified in models.py: class Book(models.Model): created = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(MyUser)

Solution 1:

classReadBy(models.Model):
    ... snip ...
    book = models.ForeignKey(Book, null=True, blank=True)

Solution 2:

OK I solved this.

I forgot to define the book field in the ReadBySerializer as PrimaryKeyRelatedField:

book = serializers.PrimaryKeyRelatedField(source='book.id')

In fact it seems like I can remove this line altogether since PrimaryKeyRelatedField is default if nothing is specified.

Post a Comment for "Cannot Post Entry Specifying Specific Id If The Id Is Specified As Foreignkey In Django"