My serializer:
class TaskSerializer(serializers.ModelSerializer):
class Meta:
model = Task
fields = "__all__"
def create(self, validated_data):
try:
print(validated_data)
print(validated_data.author)
task = Task.objects.create(**validated_data)
return task
except BaseException as e:
print(e)
raise HTTP_400_BAD_REQUEST
my view:
class TaskCreateApiView(generics.CreateAPIView):
serializer_class = TaskSerializer
my model:
from django.db import models
from django.contrib.auth.models import User
class Task(models.Model):
content = models.CharField(
default="",
max_length=255,
)
author = models.ForeignKey(
User,
on_delete=models.CASCADE,
null=True,
)
category = models.CharField(
default="",
max_length=255,
)
def __str__(self):
return str(self.id) + self.content
My log from serializer:
{‘content’: ‘test2’, ‘category’: ‘test’, ‘author’: <User: zaq1>}
‘dict’ object has no attribute ‘author’
print(validated_data.author)
^^^^^^^^^^^^^^^^^^^^^
AttributeError: ‘dict’ object has no attribute ‘author’
How can I access author? I see it exists as <User:zaq1> but can’t seem to access it
>Solution :
The error is because you print validate_data.author, whereas it should be validate_data['author']:
class TaskSerializer(serializers.ModelSerializer):
class Meta:
model = Task
fields = '__all__'
def create(self, validated_data):
try:
print(validated_data)
print(validated_data['author'])
task = Task.objects.create(**validated_data)
return task
except BaseException as e:
print(e)
raise HTTP_400_BAD_REQUEST
That being said, normally manually creating in a serializer is a (serious) antipattern: a lot of work in the serializer goes to creating objects with many-to-many fields, or deeply nested data.