[Answered ]-How to add default data to django model

1👍

CircularDependencyError

The circular dependency error is encountered when a file being called is associated with a dependency, which has the file being called as its dependency.

In the file main_app/001_initial.py, you added the dependency main_app/001_initial.py by adding the line:

dependencies = [
    ('main_app', '0001_initial')
]

On migration, the confusion arises whether to import the file main_app/001_initial.py or the dependency main_app/001_initial.py whose dependency is the file main_app/001_initial.py.
Hence, creating a circular dependency pattern.

Adding default values.

Adding multiple rows of data from migration file is not part of a good coding paradigm. You would want to use a different method.

Add default values to model itself.

These values will only help to add default values when saving one instance at a time.

class Records(models.Model):
    alias = models.CharField(max_length=17, unique=True, default="ACCORD")
    status = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    
    def __str__(self):
        return self.alias

Now there are multiple ways to populate the table with data.

  1. Link the django app to the database with data rows already in place.
  2. Add a serializer function BulkCreate to add values in bulk.
  3. Use the command line shell manually to create model instances that would populate the database table. You can read about using python manage.py shell and python manage.py shellplus.
  4. Use a python script to add the data by creating model instances with the desired values.

Another tip

Instead of using a list_data function in models.py, using a django serializer would serve more functionality and is a better way to code.

The idea is to keep models.py as clean as possible with only the attribute definitions there.

Leave a comment