2

I want to solve my problem, I was looking for answer but I can't find any solution.

Let's say I have a Model:

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

There is only one field. What I like to do is to create additional button in admin panel and use this button to automatically create 100 AccessCodes in my database. So there are 2 questions:

  1. How to create custom button in admin panel to perform some action with it?
  2. How to automatically create 100 objects of some model with one step?

The key_generator is my custom function to generate random string as a default value.

1 Answer 1

1

You can use bulk_create method introduced in Django 1.4,

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

However there are some problems with this approach, from 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.

To add action to admin page, please check this answer with details how to do it.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank for your quick reply. I have a question to first point. What does exactly mean that save() method will not be called? Does it mean that those objects will not be saved in database? Would I have a possibility to operate on those objects (edit, delete)?
No, it will be saved in database, but the django model save method will not be called, this means if you have overridden save method with custom one to implement some custom logic on save, similar to this example: docs.djangoproject.com/en/1.4/topics/db/models/… then this logic will not apply with bulk_create

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.