user518851726681
user518851726681

Reputation: 147

Django - Is this possible that the add default values when model is creating?

I want to add some default values in my database when the related model is creating with makemigrations command.

For example I have this as model;

class BaseModel(models.Model):
      created_at = models.DateTimeField(auto_now_add=True, verbose_name='Created Date')
      modified_at = models.DateTimeField(auto_now=True, verbose_name='Update Date')
      is_deleted = models.BooleanField(default=False, verbose_name='Deleted')

      class Meta:
          abstract = True

class ModelType(BaseModel):
      description = models.CharField(verbose_name='Name', max_length=225 )

and as I said before I want to add some default values ("value1", "value2", "value3", "value4") for my ModelType table. Is that possible?

Upvotes: 2

Views: 1329

Answers (2)

GaretJax
GaretJax

Reputation: 7780

If you want to always add the default data when you execute a given migration, the safest way is to use a datamigration (as suggested by @Kos).

To create a data migration, use ./manage.py makemigrations <app_label> --empty and manually add the required code to populate the data.

I normally use a custom operation which executes a get_or_create on the specified model. Add this code to either the migration file itself or somewhere where it can be imported from:

from django.db import migrations


def noop(apps, schema_editor):
    pass


class EnsureInstanceCreated(migrations.RunPython):
    def __init__(self, app_name, model_name, attrs, defaults=None):
        super(EnsureInstanceCreated, self).__init__(self.add_instance, noop)
        self.app_name = app_name
        self.model_name = model_name
        self.attrs = attrs
        self.defaults = defaults

    def add_instance(self, apps, schema_editor):
        Model = apps.get_model(self.app_name, self.model_name)
        Model.objects.get_or_create(
            defaults=self.defaults,
            **self.attrs
        )

Then, in the migration itself:

from django.db import migrations
from myproject.utils.migrations import EnsureInstanceCreated


class Migration(migrations.Migration):

    dependencies = [
        ('myproject', '000x_auto_...'),
    ]

    operations = [
        EnsureInstanceCreated('myapp', 'ModelType', attrs={
            'description': 'value1',
        }, defaults={
            # ...
        }),
        EnsureInstanceCreated('myapp', 'ModelType', attrs={'description': 'value2'}),
        EnsureInstanceCreated('myapp', 'ModelType', {'description': 'value3'}),
    ]

Upvotes: 3

Piyush Das
Piyush Das

Reputation: 670

Apparently there is a way. You can use Fixtures to initialize models with data.

Refer to this piece of documentation: https://docs.djangoproject.com/en/1.10/howto/initial-data/

Upvotes: 0

Related Questions