主键由数据库分配,因此您必须等待模型行保存在数据库上。
首先将数据分为两个模型,缩略图位于子模型上:
from django.db import models
from .fields import CMSImageField
class CMSDocument(models.Model):
title = models.CharField(max_length=50)
class CMSMediaDocument(CMSDocument):
thumb = CMSImageField(upload_to='./media/', blank=True)
如您所见,我使用缩略图的自定义字段而不是 ImageField。
然后创建一个 fields.py 文件,您应该在其中重写 ImageField 继承的 FileField 类的 pre_save 函数:
from django.db import models
class CMSImageField(models.ImageField):
def pre_save(self, model_instance, add):
file = super(models.FileField, self).pre_save(model_instance, add)
if file and not file._committed:
# Commit the file to storage prior to saving the model
file.save('%s.png' % model_instance.pk, file, save=False)
return file
由于 CMSMediaDocument 继承自 CMSDocument 类,因此在调用 pre_save 时,渐进式 PK 已保存在数据库中,因此您可以从模型_实例.
我测试了代码,应该可以正常工作。
测试中使用的admin文件:
from django.contrib import admin
from .models import CMSMediaDocument
admin.site.register(CMSMediaDocument)