我想在上传后将图像文件大小保存在数据库中。在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)
提前谢谢
您可以通过存储在} [Django-doc]属性来获取此信息:
FileField
中的FieldFile
的^{会议将:
因此,您可以通过以下方式获得文件的大小:
相关问题 更多 >
编程相关推荐