Skip to main content
 首页 » 编程设计

python之在 Django 中使用一个按钮创建模型的多个对象

2025年05月04日22qq号

我想解决我的问题,我一直在寻找答案,但找不到任何解决方案。

假设我有一个模型:

class AccessCode(models.Model): 
    access_code = models.CharField(max_length=100, verbose_name='Access code', 
    unique=True, default=key_generator) 
    def __str__(self): 
        return self.access_code 
    def __unicode__(self): 
       return self.access_code 

只有一个字段。我喜欢做的是在管理面板中创建附加按钮,并使用此按钮在我的数据库中自动创建 100 个访问代码。 所以有2个问题:

  1. 如何在管理面板中创建自定义按钮来执行某些操作?
  2. 如何一步自动创建某个模型的100个对象?

key_generator 是我的自定义函数,用于生成随机字符串作为默认值。

请您参考如下方法:

可以使用Django 1.4引入的bulk_create方法,

AccessCode.objects.bulk_create([AccessCode() for i in range(100)]) 

但是这种方法存在一些问题,来自django doc

This has a number of caveats though:

- The model’s save() method will not be called, and the pre_save and post_save signals will not be sent. 
- It does not work with child models in a multi-table inheritance scenario. 
- If the model’s primary key is an AutoField it does not retrieve and set the primary key attribute, as save() does. 

要向管理页面添加操作,请检查this answer详细说明如何操作。