在 DRF 中发送完整图像 url

Send full image url in DRF

我正在尝试在 DRF 的 API 中获取完整图像 URL 我正在尝试使用 build_absolute_uri 但我一直收到错误 'image' 属性没有与之关联的文件。

serializer.py:

class VesselInfoSerializer(serializers.ModelSerializer):

    image_url = serializers.SerializerMethodField()

    def get_image_url(self, Vessel):
        request = self.context.get('request')
        image_url = Vessel.image.url
        return request.build_absolute_uri(image_url)

    vessel_component_count = serializers.IntegerField(
        source='vessel_components.count',
        read_only=True
    )
    vessel_inventory_category_count = serializers.IntegerField(
        source='vessel_inventory_category.count',
        read_only=True
    )
    vessel_inventory_item_count = serializers.IntegerField(
        source='category_items.count',
        read_only=True
    )

    class Meta:
        model = Vessel
        fields = '__all__'

models.py:

class Vessel(models.Model):
    name = models.CharField(max_length=255)
    imo = models.CharField(max_length=255)
    image = models.ImageField(blank=True, upload_to='vessel_image')

    def __str__(self):
        return self.name

观点:

@api_view(['GET'])
def getVesselInfo(request):
    vessels = Vessel.objects.all()
    vSerializer = VesselInfoSerializer(
        vessels, many=True, context={"request": request})
    return Response(vSerializer.data)

您可能应该检查 url 不是 None :

    def get_image_url(self, Vessel):
        request = self.context.get('request')
        image_url = Vessel.image.url if Vessel.image and hasattr(Vessel.image, 'url') else None
        if image_url:
            return request.build_absolute_uri(image_url)
        return None