I want to do the following:
models.py
class MyModel(TimeStampedModel, models.Model):
name = models.CharField(max_length=100)
owner = models.ForeignKey(settings.AUTH_USER_MODEL)
serializers.py
class MyModelSerializerCreate(serializers.ModelSerializer):
class Meta:
model = MyModel
fields = (
'name',
)
And I would like to add as the owner of the current user in request.user. I am currently adding this to my point of view by first updating request.data with the user and then passing the updated data to my serializer.
data = request.data
data["owner"] = request.user.pk
serializer = self.get_serializer(data=data)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
I would like to do this directly in my serializer, but I can’t find a way to do it right, because it seems like data validation for me. Is that a good idea? Should I stick to this logic in my views or move it to my serializer?
source
share