Django blank FileField如何序列化而不出错
我的模型中定义了一个文件字段,如下所示:Django blank FileField如何序列化而不出错,django,django-models,django-serializer,Django,Django Models,Django Serializer,我的模型中定义了一个文件字段,如下所示: class Profile(models.Model): ... profile_picture = models.FileField(blank=True) from django.forms.models import model_to_dict class ProfileView(APIView): def get(self, request, format='json'): profile = ...
class Profile(models.Model):
...
profile_picture = models.FileField(blank=True)
from django.forms.models import model_to_dict
class ProfileView(APIView):
def get(self, request, format='json'):
profile = ...
profile_serialized = model_to_dict(profile)
return Response(profile_serialized, status=status.HTTP_200_OK)
然后,我有一个JSON视图,如下所示:
class Profile(models.Model):
...
profile_picture = models.FileField(blank=True)
from django.forms.models import model_to_dict
class ProfileView(APIView):
def get(self, request, format='json'):
profile = ...
profile_serialized = model_to_dict(profile)
return Response(profile_serialized, status=status.HTTP_200_OK)
我正在使用DRF,但我不关心DRFmodel_to_dict
将模型转换为dictionary,因此我可以将其作为JSON输出。但是,我不断收到验证错误:
ValueError:“profile\u picture”属性没有与之关联的文件
如果字段为空,则无法序列化它。我应该如何解决这个问题?我应该在进行检查的模型中创建一个@property
函数,还是有更好的方法
谢谢 我最终使用了DRF序列化程序,而不是
model\u to\u dict
,一切都很好。相关:那么,序列化模型的正确方法是什么?我找不到任何与此相关的内容。我最终使用了DRF序列化程序。