Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Rest Framework: How to set a field to null via PATCH request?

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!

like image 444
Robert Broersma Avatar asked Nov 02 '17 13:11

Robert Broersma


People also ask

How do you set a field to null in Django?

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.

What is HyperlinkedModelSerializer?

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.

What is serializer method field in Django?

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.

How does serializer work on Django REST framework?

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.


2 Answers

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}
like image 87
Linovia Avatar answered Oct 18 '22 04:10

Linovia


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

like image 1
souldeux Avatar answered Oct 18 '22 04:10

souldeux