在Django Admin中上传多个图像

时间:2018-07-02 18:19:24

标签: python django django-rest-framework django-admin

models.py

class Video(models.Model):
    title = models.CharField(max_length=100, blank=True, default='')
    details = models.TextField()

class VideoDetails(models.Model):
    video = models.ForeignKey(Video, on_delete=models.CASCADE, related_name='videos')
    images = models.ImageField(upload_to='images/video/%Y/%m/%d')

serializers.py

class VideoDetailsSerializer(serializers.ModelSerializer):
    class Meta:
        model = VideoDetails
        fields = '__all__'

class VideoSerializer(serializers.ModelSerializer):
    class Meta:
        model = Video
        fields = '__all__'

admin.py

class VideoDetailsInline(admin.TabularInline):
    model = VideoDetails

class VideoAdmin(admin.ModelAdmin):
    inlines = [VideoDetailsInline]

admin.site.register(Video, VideoAdmin)

enter image description here enter image description here

如上所示,我为视频2上传了3张图像。但是,在我的VideoList视图中,我没有得到这些图像的网址。

views.py

class VideoList(viewsets.ModelViewSet):
    serializer_class = VideoSerializer
    queryset = Video.objects.all()

如何将VideoDetail中的图片网址附加到queryset的{​​{1}}上?需要您的帮助...

1 个答案:

答案 0 :(得分:0)

据此更改文件,不要忘记配置 MEDIA_URL

models.py

import os
from django.conf import settings

class VideoDetails(models.Model):
    video = models.ForeignKey(Video, on_delete=models.CASCADE, related_name='videos')
    images = models.ImageField(upload_to='images/video/%Y/%m/%d')

    def get_absolute_image_url(self):
        return os.path.join(settings.MEDIA_URL, self.images.url)

serializers.py

class VideoDetailsSerializer(serializers.ModelSerializer):

    image_url = serializers.URLField(source='get_absolute_image_url', read_only=True)

    class Meta:
        model = VideoDetails
        fields = ('video', 'image_url')


class VideoSerializer(serializers.ModelSerializer):

    video_details = VideoDetailsSerializer(many=True, read_only=True)

    class Meta:
        model = Video
        fields = ('title', 'details', 'video_details')