在我的django应用程序中,我有一个“Incidence”模型,它有几个FileField和ImageField。我想用Django Rest Framework创建一个端点来检索关于"Incidence"的信息,但到目前为止我所做的只是检索文件的url。我需要返回的格式,可以由客户端应用程序下载的文件,如二进制数据或其他建议。我该怎么做?这就是我目前所做的
模型定义:
class Incidence(BasicAuditModel):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True)
geom = models.PointField(verbose_name=_("Localización"), srid=4326, blank=True, null=True)
name = models.CharField(_("Nombre"), max_length=255)
incidence_type = models.CharField(_("Tipo incidente"), max_length=50, choices=INCIDENCE_TYPE_CHOICES, default="tipo1")
description = models.TextField(_("Descripción"), blank=True, null=True)
status = models.CharField(_("Status"), max_length=50, choices=STATUS_CHOICES, default="creado")
image1 = models.ImageField(verbose_name=_("Foto 1"), upload_to="incidencia_fotos",
null=False, blank=False)
image2 = models.ImageField(verbose_name=_("Foto 2"), upload_to="incidencia_fotos",
null=False, blank=False)
image3 = models.ImageField(verbose_name=_("Foto 3"), upload_to="incidencia_fotos",
null=False, blank=False)
audio = models.FileField(verbose_name=_("Audio"), upload_to="incidencia_audioa",
null=False, blank=False)
video = models.FileField(verbose_name=_("Video"), upload_to="incidencia_video",
null=False, blank=False)
def __str__(self):
return self.name
class Meta:
db_table = 'sini_incidence'
managed = True
verbose_name = 'Incidencia'
verbose_name_plural = 'Incidencias'
class BasicAuditModel(models.Model):
created_by = models.ForeignKey(settings.AUTH_USER_MODEL,
related_name="+",
verbose_name=_("Creado por"),
null=True,
blank=False,
on_delete=models.SET_NULL)
modified_by = models.ForeignKey(settings.AUTH_USER_MODEL,
related_name="+",
verbose_name=_("Modificado por"),
null=True,
blank=False,
on_delete=models.SET_NULL)
created = models.DateTimeField(auto_now_add=True, verbose_name=_("Fecha creado"))
modified = models.DateTimeField(auto_now=True, verbose_name=_("Fecha modificado"))
序列化程序类:
from rest_framework_gis.serializers import GeoFeatureModelSerializer
class IncidenceSerializer(GeoFeatureModelSerializer):
class Meta:
model = Incidence
geo_field = "geom"
fields = ('id','geom','name','incidence_type',
'description','status', 'image1', 'image2', 'image3', 'audio', 'video')
extra_kwargs = {'geom': {'required': True}}
read_only_fields = ['id','created_by', 'modified_by', 'created','modified']
这就是观点:
class IncidenceAPIRetrieve(generics.RetrieveAPIView):
authentication_classes = [JWTAuthentication]
permission_classes = (IsAuthenticated,)
queryset = Incidence.objects.all()
serializer_class = IncidenceSerializer
这就是我得到的JSON。正如您所看到的,端点返回文件的url。我需要能够下载文件。
1条答案
按热度按时间h79rfbju1#
基本上,问题是您返回的内容是
application/json
类型。但是你仍然可以解析json并在客户端用JavaScript呈现图像的url,但是如果只是一个图像,这是一种优化的方式。如果有多个图像,那么唯一的选择是返回图像的url并在客户端呈现它们,因为
return
将结束函数。检查这篇文章是否解决了你的问题(返回图像的内容,只有当你想渲染单个图像的内容时才使用这个,因为我们之前已经讨论过原因):-如何使用Django REST框架返回生成的文件下载?