Issue
In my Django serializer, I have a validate() method.
In it, I want to access the value of one of the serializer's fields. How would I do this?
I'm using Python 3.10.2 and Django 3.2.23.
Previous answers here have suggested using self.initial_data.get("field_name"))
but that doesn't work for my version of Django (message: AttributeError: 'MySerializer' object has no attribute 'initial_data').
class MySerializer:
models = models.MyModel
class Meta:
fields = "my_field"
def validate(self, data):
# Want to get the value of my_field here
Many thanks in advance for any assistance.
Solution
The solution was to add data into the associated Django view's context - in my case, an id - and populate it when the serializer is defined.
View:
def put(self, request, *args, **kwargs):
serializer = MySerializer(
instance=instance,
data=request.data,
context={"user_id": self.request.user.id},
)
Serializer:
def validate(self, data):
context = getattr(self, "context", None)
if context is None:
return data
user_id = context.get("user_id")
obj = MyEntity.objects.get(user_id=user_id)
This also works for nested serializers: the context value automatically gets supplied for each.
Answered By - GarlicBread
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.