I have a Model
and a ModelSerializer
with this field:
models.py:
leftovers_from = models.ForeignKey('DayPlanning', null=True, blank=True, related_name='extra_for', on_delete=models.CASCADE)
serializers.py:
leftovers_from_id = serializers.PrimaryKeyRelatedField(queryset=DayPlanning.objects.all(), source='leftovers_from', write_only=True, required=False)
Now I can perfectly fine create a new object for this model using a POST request (both with or without this field being null
/None
/empty.)
However when I try to update the field using PATCH I can only update it with a different value (a PK of the Foreign model). I've tried passing null
, ''
, 0
and -1
to leftovers_from_id
, however the result is either This field cannot be empty
or PK 0 not found
.
How do I clear this field using a PATCH request?
Thanks!
null=True will make the field accept NULL values. Blank values for Django field types such as DateTimeField or ForeignKey will be stored as NULL in the database.
HyperlinkedModelSerializer is a layer of abstraction over the default serializer that allows to quickly create a serializer for a model in Django. Django REST Framework is a wrapper over default Django Framework, basically used to create APIs of various kinds.
Serializer fields handle converting between primitive values and internal datatypes. They also deal with validating input values, as well as retrieving and setting the values from their parent objects.
Serializers in Django REST Framework are responsible for converting objects into data types understandable by javascript and front-end frameworks. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.
Note that required
means the field may be omitted for creation or "full" update. Patch bypasses the required
fields to achieve a partial update.
Therefore you'll need to set allow_null
argument to True:
leftovers_from_id = serializers.PrimaryKeyRelatedField(
queryset=DayPlanning.objects.all(),
source='leftovers_from', write_only=True,
required=False, allow_null=True,
)
Then you should be able to PATCH with:
{'leftovers_from_id': null}
To clear the relation, you should set the value to None
. Since you specifically mentioned PATCH
methods, make sure you're aware of the partial
argument as well: http://www.django-rest-framework.org/api-guide/serializers/#partial-updates
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With