据我所知,将字段动态注入 django 模型并非易事。如果您想尝试,这可以成为您的起点。
类似的帖子可以在这里找到。
http://www.sixpearls.com/blog/2013/feb/django-class_prepared-signal/
from django.db.models.signals import class_prepared
def add_image_fields(sender, **kwargs):
"""
class_prepared signal handler that checks for the model massmedia.Image
and adds sized image fields
"""
if sender.__name__ == "Image" and sender._meta.app_label == 'massmedia':
large = models.ImageField(upload_to=".", blank=True, verbose_name=_('large image file'))
medium = models.ImageField(upload_to=".", blank=True, verbose_name=_('medium image file'))
small = models.ImageField(upload_to=".", blank=True, verbose_name=_('small image file'))
large.contribute_to_class(sender, "large")
medium.contribute_to_class(sender, "medium")
small.contribute_to_class(sender, "small")
class_prepared.connect(add_image_fields)
它基本上附加了一个函数来创建这些字段。
您可以捕获 class_prepared 信号并列出所有字段,如果它是图像字段,则贡献给类 image_field_thumbnail
要获取属于某个模型的所有字段,可以使用get_fields