如何在Django模型中获得图像文件大小?

2024-10-03 04:26:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在上传后将图像文件大小保存在数据库中。在django模型中如何实现这一点?如果我能在视图中获得大小,它也会起作用。但是,由于一个社区帖子中可以有多个图片,我无法获得每个图片的大小。 My models.py文件:

from django.db import models
import os


class Community(models.Model):
    title = models.CharField(max_length=100)
    description = models.TextField(max_length=500)

    def __str__(self) -> str:
        return self.title


class CommunityImages(models.Model):
    post = models.ForeignKey(Community, on_delete=models.CASCADE)
    height = models.IntegerField(null=True, blank=True)
    width = models.IntegerField(null=True, blank=True)
    image = models.ImageField(upload_to='communityImages/%Y/%m/%d', blank=True, null=True, height_field='height', width_field='width')
    @property
    def images_exists(self):
        return self.communityImages.storage.exists(self.communityImages.name)
    def community(self):
        return self.post.id
    def __str__(self):
        return "%s %s " % (self.post_id, self.image, )
    class Meta:
        verbose_name_plural = "Community Images"

My views.py文件:

from django.http import JsonResponse
from .models import CommunityImages, Community
import json
import os


def image_detail(request, post_id):
    community_post = {}
    communityPostImages = list(CommunityImages.objects.filter(post=post_id).values('id','image', 'height', 'width'))
    
    for i in range(len(communityPostImages)):
        communityPostImages[i]['img_name'] = os.path.split(communityPostImages[i]['image'])[-1]
        communityPostImages[i]['type'] = os.path.splitext(communityPostImages[i]['img_name'])[-1].replace('.', '')
        communityPostImages[i]['dimension'] = str(communityPostImages[i]['height']) + "x" + str(communityPostImages[i]['width'])

    community_post['communityPostImages'] = communityPostImages
    data = json.dumps(community_post, indent=4, sort_keys=False, default=str)
    return JsonResponse(data, safe=False)

提前谢谢


Tags: communityimageimportselfidtruereturnos
1条回答
网友
1楼 · 发布于 2024-10-03 04:26:18

您可以通过存储在FileField中的FieldFile^{} [Django-doc]属性来获取此信息:

The result of the underlying Storage.size() method.

会议将:

Returns the total size, in bytes, of the file referenced by name. For storage systems that aren’t able to return the file size this will raise NotImplementedError instead.

因此,您可以通过以下方式获得文件的大小:

some_community_image.image.size  # size in bytes

相关问题 更多 >