How to make ForeignKey play nice with None in DRF?

Viewed 2212

In Django REST Framework, is there an easy way to work with nullable ForeignKeys and serializers? I keep running into issues (mainly in my tests) where I'll serialize a model that has a nullable foreign key, send the data back to DRF and I get the error 'Incorrect type. Expected pk value, received str.'

Example:

class Book(models.Model):
    publisher = models.ForeignKey(Publisher, null=True, blank=True)

class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book

class BookViewSet(viewsets.ViewSet):
    model = Book
    serializer_class = BookSerializer

and the usual implementation with URLs, routes, and all that.

Then, in shell:

>>> from django.test.client import Client
>>> client = Client()
>>> book = Book()
>>> serializer = BookSerializer(book)
>>> response = client.post('/books/', serializer.data)
>>> response.data
{'publisher': ['Incorrect type.  Expected pk value, received str.']}

Seems like this should work since the data being posted came directly from DRF's serializer. Has anyone else encountered this? What are the best practices here?

1 Answers
Related