在django的models中的图片字段,按照时间归档到设定的media静态目录下,并自动更名。
from django.db import models
import os
import time
def update_filename(instance, filename):
path = ‘image/book/’+time.strftime(“%Y/%m”,time.localtime())
ext = filename.split(‘.’)[-1]
unix_time = int(time.time())
format = str(unix_time)+’.’+ext
return os.path.join(path, format)
class Book(models.Model):
title = models.CharField(max_length=100,verbose_name=’书籍名称’)
publishDate = models.DateField()
image = models.ImageField(default=’image/book.png’, upload_to=update_filename, verbose_name=’封面’, max_length=100)
publish = models.ForeignKey(Publish,on_delete=models.CASCADE,verbose_name=’出版社’)
author = models.ManyToManyField(Author,verbose_name=’作者’)
class Meta:
verbose_name_plural = ‘书籍’
verbose_name = ‘书籍’
def __str__(self):
return self.title