我有一个名为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'
任何建议将不胜感激!
答案 0 :(得分:5)
错误可能出在您的print()
语句中。如果serializer
有效,则序列化的数据将在 serializer.data
中可用。
因此,应该是
serializer.data['name']
而不是serializer.name