我有以下型号:
def get_file_path(instance, filename):
return 'files/{0}/{1}'.format(instance.user.username, filename)
class File(models.Model):
fid = models.UUIDField(primary_key=True, default=uuid.uuid4)
user = models.ForeignKey(settings.AUTH_USER_MODEL)
file = models.FileField(upload_to=get_file_path)
当我尝试使用例如serializers.serialize('json', File.objects.all())
序列化此模型时,我得到:
u'[{"model": "app_name.file", "pk": "45f616b4-d028-488e-83c5-878ce1028018", "fields": {"user": 1, "file": "files/username/filename.txt"}}]'
我希望序列化的json还包含file_obj.file.url
返回的文件字段的url,所以我添加了一个属性字段,如下所示:
class File(models.Model):
fid = models.UUIDField(primary_key=True, default=uuid.uuid4)
user = models.ForeignKey(settings.AUTH_USER_MODEL)
file = models.FileField(upload_to=get_file_path)
def _get_file_url(self):
"Returns file's url"
return self.file.url
url = property(_get_file_url)
但属性字段url
仍未序列化。所以我尝试通过扩展serializers.ModelSerializer
来为模型编写自定义序列化器:
class FileSerializer(serializers.ModelSerializer):
class Meta:
model = File
fields = ('fid', 'user', 'file', 'url')
哪个不起作用,我得到'module' object has no attribute 'ModelSerializer'
。是因为django没有ModelSerializer类而只有django rest_framwork吗?如果是这样,如果我只使用django而不是django rest框架,我该如何解决?
感谢。
答案 0 :(得分:0)
您必须在视图中手动构建包含您要返回的数据的dict,然后使用from django.http.response import JsonResponse
来序列化结果。
def single_object_representation(obj):
return {
'fid': obj.fid,
'user': obj.user.username,
'url': obj._get_file_url()
}
def demo_view(request):
objects_to_serialize = File.objects.all()
result = [single_object_representation(obj) for obj in objects_to_serialize]
return JsonResponse(result, safe=False)
见这里:https://docs.djangoproject.com/en/2.0/topics/serialization/#subset-of-fields
但请确保它适用于您的财产。对于某些字段(如用户),您应使用双字母下划线表示法__
,例如user__username
首先安装drf:
pip install djangorestframework
然后,如果您的序列化程序仍然存在问题,请尝试SerializerMethodField
(如果有疑问请参阅文档:http://www.django-rest-framework.org/api-guide/fields/#serializermethodfield)
from rest_framework import serializers
class FileSerializer(serializers.ModelSerializer):
url = serializers.SerializerMethodField()
class Meta:
model = File
fields = ('fid', 'user', 'file', 'url')
def get_url(self):
return self. _get_file_url()