django 无法访问对象的属性,尽管它存在

vwhgwdsa  于 2023-11-20  发布在  Go
关注(0)|答案(1)|浏览(178)

我的序列化器:

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

字符串
我的看法:

class TaskCreateApiView(generics.CreateAPIView):
    serializer_class = TaskSerializer


我的模型:

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


我从序列化器的日志:
请输入'content':'test 2','category':'test','author':<User: zaq1>}
“dict”对象没有属性“author”print(validated_data.author)^^
如何访问author?我看到它以<User:zaq1>的形式存在,但似乎无法访问它

5hcedyr0

5hcedyr01#

这个错误是因为你打印了validate_data.author,而它应该是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

字符串
也就是说,通常在序列化器中手动创建是一种(严重的)反模式:序列化器中的大量工作都是创建具有多对多字段或深度嵌套数据的对象。

相关问题