gpt4 book ai didi

django - Django Rest Framework如何访问序列化器中的字段

转载 作者:行者123 更新时间:2023-12-01 15:30:52 25 4
gpt4 key购买 nike

我有一个名为Video的模型

class Video(models.Model):
created = models.DateTimeField(auto_now_add=True)
name = models.CharField(max_length=100, blank=False, null=False, default='', unique=True)
file = models.FileField(upload_to='videos/', blank=False, null=False)
owner = models.ForeignKey('auth.User', related_name='videos', on_delete=models.CASCADE, verbose_name='')

def __str__(self):
return self.name + ': ' + self.file.name

class Meta:
ordering = ('created',)

及其序列化器:
class VideoSerializer(serializers.ModelSerializer):
owner = serializers.ReadOnlyField(source='owner.username')

class Meta:
model = Video
fields = ['name', 'file', 'owner']

我试图访问序列化程序中的字段,因为我需要它进行一些处理:
def post(self, request):
serializer = VideoSerializer(data=request.data)
if serializer.is_valid():
# I need the name of the file!!!!!
# accessing the fields below
print(serializer.name)
print(serializer.file.name)
# accessing the fields above
serializer.save(owner=request.user)
videos = Video.objects.filter(owner=request.user)
return Response({'videos': videos, 'serializer': VideoSerializer(), 'style': self.style})
return Response(data=None, status=status.HTTP_400_BAD_REQUEST, template_name='videoserver/error.html')

但是当我发出请求时,它将报告此错误:
AttributeError: 'VideoSerializer' object has no attribute 'name'


AttributeError: 'VideoSerializer' object has no attribute 'file'

任何建议将不胜感激!

最佳答案

错误可能在您的print()语句中。如果serializer有效,则序列化的数据将在 serializer.data 中可用。

因此,它应该是

serializer.data['name']
而不是
serializer.name

关于django - Django Rest Framework如何访问序列化器中的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52221362/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com