I am new to DRF. I read the API docs, maybe it is obvious but I couldn\'t find a handy way to do it.
I have an Answer object which has one-to-one relationship with a
A better and more generalized way to apply this would be to update the ModelSerializer object with a potential instance if it exists. This allows DRF to follow standard protocols and can be abstracted across models easily.
To keep things generic, start by making an UpdateOrCreate class to be inherited alongside the modelSerializer on instantiation. In this, add the def update_or_create_helper.
Then inherit the UpdateOrCreate class for each Serializer you want the functionality with and add a simple is_valid def specific to that model.
serializers.py
class UpdateOrCreate:
def update_or_create_helper(self, obj_model, pk):
# Check to see if data has been given to the serializer
if hasattr(self, 'initial_data'):
# Pull the object from the db
obj = obj_model.objects.filter(pk=self.initial_data[pk])
# Check if one and only one object exists with matching criteria
if len(obj)==1:
# If you want to allow for partial updates
self.partial = True
# Add the current instance to the object
self.instance = obj[0]
# Continue normally
return super().is_valid()
...
# Instantiate the model with your standard ModelSerializer
# Inherit the UpdateOrCreate class
class MyModelSerializer(serializers.ModelSerializer, UpdateOrCreate):
class Meta:
model = MyModel
fields = ['pk', 'other_fields']
# Extend is_valid to include the newly created update_or_create_helper
def is_valid(self):
return self.update_or_create_helper(obj_model=MyModel, pk='pk')