Reputation: 433
It seems no matter what I do I cannot get the parent
field to not be required. I'm using DRF version 3.2.3 and Django 1.8.4.
Model definition of field:
parent = models.ForeignKey(
"self", verbose_name=_("Parent"), blank=True, null=True,
default=None, related_name='children')
The model also has a unique_together
:
unique_together = (('owner', 'parent', 'name',),)
Serializer definition of field:
parent = serializers.HyperlinkedRelatedField(
view_name='category-detail', queryset=Category.objects.all(),
required=False)
I'm writing unittests and the response code is 400 with a text response of:
{'parent': [u'This field is required.']}
The parent
field is a ForeignKey back to another row in the same table.
Gals/Guys any ideas how to fix this?
Upvotes: 4
Views: 634
Reputation: 6013
Sometimes a field can be implicitly made required
by some other piece of code. One case I encountered is the model-level unique_together
constraint, that makes all included fields required on the serializer level. From the doc:
Note: The
UniqueTogetherValidation
class always imposes an implicit constraint that all the fields it applies to are always treated as required. Fields with default values are an exception to this as they always supply a value even when omitted from user input.
I think you will just have to override the serializer save
or viewset create/update
to set the value to what you want at this point. Another option is to try to remove the UniqueTogetherValidator
from the serializer's validators in its __init__
. On the other hand I think it is added for a reason.
It is worth mentioning that in admin and anywhere else ModelForm
is used, these fields won't be required because ModelForm
is another thing entirely and it handles the validation in its own way.
Upvotes: 3