In Django REST framework (2.1.16) I have a model with nullable FK field type
, but POST creation request gives 400 bad request
which says that field is required.
My model is
class Product(Model):
barcode = models.CharField(max_length=13)
type = models.ForeignKey(ProdType, null=True, blank=True)
and serializer is:
class ProductSerializer(serializers.ModelSerializer):
class Meta:
model = Product
exclude = ('id')
I've tried to add type
explicitly to serializer like
class ProductSerializer(serializers.ModelSerializer):
type = serializers.PrimaryKeyRelatedField(null=True, source='type')
class Meta:
model = Product
exclude = ('id')
and it has no effect.
From http://django-rest-framework.org/topics/release-notes.html#21x-series I see that there was a bug, but it was fixed in 2.1.7.
How should I change serializer to properly handle my FK field?
Thanks!
UPDATE: from the shell it gives
>>> serializer = ProductSerializer(data={'barcode': 'foo', 'type': None})
>>> print serializer.is_valid()
True
>>>
>>> print serializer.errors
{}
but without type=None:
>>> serializer = ProductSerializer(data={'barcode': 'foo'})
>>> print serializer.is_valid()
False
>>> print serializer.errors
{'type': [u'This field is required.']}
>>> serializer.fields['type']
<rest_framework.relations.PrimaryKeyRelatedField object at 0x22a6cd0>
>>> print serializer.errors
{'type': [u'This field is required.']}
in both cases it gives
>>> serializer.fields['type'].null
True
>>> serializer.fields['type'].__dict__
{'read_only': False, ..., 'parent': <prodcomp.serializers.ProductSerializer object at 0x22a68d0>, ...'_queryset': <mptt.managers.TreeManager object at 0x21bd1d0>, 'required': True,
exclude
options are missing a comma, that'd force them to be treated as tuples.exclude = ('id',)
– Forecastsource='type'
, since in this case the field name already matches the source you want to use. – Forecastsource='type'
– Kinkajou