如何在 DRF 中获取完整的 url 图像?

How can I get the full url of the image in DRF?

我英语不好。希望大家理解。

  1. 日记中可以有多张图片。
  2. Diary 和 DiaryImage 是 1:N 关系。

这是我的模型

from django.db import models

from userSystem.models import User


class Diary(models.Model):
    id = models.BigAutoField(primary_key=True)
    user = models.ForeignKey(User, related_name="diary_user", on_delete=models.CASCADE, null=True)
    title = models.CharField(max_length=30)
    content = models.CharField(max_length=800)
    date_created = models.DateField(auto_now_add=True)


class DiaryImage(models.Model):
    diary = models.ForeignKey(Diary, on_delete=models.CASCADE)
    image = models.ImageField(default='/media/diary/default_image.jpeg', upload_to='diary',
                              blank=True, null=True)

这是我的序列化程序

from rest_framework import serializers

from diary.models import DiaryImage, Diary


class DiaryImageSerializer(serializers.ModelSerializer):
    image = serializers.ImageField(use_url=True)

    class Meta:
        model = DiaryImage
        fields = ['image']


class DiarySerializer(serializers.ModelSerializer):
    images = serializers.SerializerMethodField()

    def get_images(self, obj):
        image = obj.diaryimage_set.all()
        return DiaryImageSerializer(instance=image, many=True).data

    class Meta:
        model = Diary
        fields = ['id', 'title', 'content', 'date_created', 'images']

    def create(self, validated_data):
        instance = Diary.objects.create(**validated_data)
        image_set = self.context['request'].FILES
        for image_data in image_set.getlist('image'):
            DiaryImage.objects.create(diary=instance, image=image_data)
        return instance

这是我的看法

from diary.serializers import DiarySerializer


class DiaryViewSet(viewsets.ModelViewSet):
    permission_classes = [permissions.IsAuthenticated, ]
    serializer_class = DiarySerializer

    def get_queryset(self):
        return self.request.user.diary_user.all()

settings.py

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

urls.py

diary_list = DiaryViewSet.as_view({"get": "list", "post": "create"})


urlpatterns = [
    path('admin/', admin.site.urls),
    path('diary/', diary_list, name="diary-list"),

] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

当我运行这段代码时,图片保存成功。 但是,加载保存的图像时,完整的 url 不会出现。

像这样,

{
    "id": 70,
    "title": "hello!",
    "content": "hello_content",
    "date_created": "2021-03-31",
    "images": [
        {
            "image": "/media/diary/DRF_Imagefield_1_xVENDCo.png"
        },
        {
            "image": "/media/diary/django_test_IGFIyYm.png"
        }
    ]
}

如何获得完整的 url 图片?

FileFieldImageField 自动尝试使用 context 中的 request 如果它被传递给序列化程序来构建绝对 url .您应该将上下文从 DiarySerializer 传递到 DiaryImageSerializer:

class DiarySerializer(serializers.ModelSerializer):
    images = serializers.SerializerMethodField()

    def get_images(self, obj):
        image = obj.diaryimage_set.all()
        return DiaryImageSerializer(instance=image, many=True, <b>context=self.context</b>).data
    
    # Rest of code