Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define default data for Django Models?

I want my application to have default data such as user types.

What's the most efficient way to manage default data after migrations?

It needs to handle situations such as, after I add a new table, it adds the default data for it.

like image 232
Dhanushka Amarakoon Avatar asked Sep 28 '16 06:09

Dhanushka Amarakoon


People also ask

What is the default data base in Django?

By default, the configuration uses SQLite. If you're new to databases, or you're just interested in trying Django, this is the easiest choice. SQLite is included in Python, so you won't need to install anything else to support your database.

How can create primary key in Django model?

By default, Django adds an id field to each model, which is used as the primary key for that model. You can create your own primary key field by adding the keyword arg primary_key=True to a field. If you add your own primary key field, the automatic one will not be added.

What is __ Str__ in Django model?

The __str__ method just tells Django what to print when it needs to print out an instance of the any model. It is also what lets your admin panel, go from this. Note: how objects are just plainly numbered. to this.

How will you define the model classes in Django?

When you make a model class in Django, consider that class the data-table, each individual instance of that class the table rows, and the attributes(e.g: title) of each table the columns. In the definition of the class Book, title seems to be a class attribute.


1 Answers

You need to create an empty migration file and Do your stuff in operations block, as explained in docs.

Data Migrations

As well as changing the database schema, you can also use migrations to change the data in the database itself, in conjunction with the schema if you want.

Now, all you need to do is create a new function and have RunPython use it

Docs explains this with an example to show ,how to communicate with your models.

From Docs

To create an empty migration file,

python manage.py makemigrations --empty yourappname 

And this is the example how to update a newly added field.

# -*- coding: utf-8 -*- from __future__ import unicode_literals  from django.db import migrations, models  def combine_names(apps, schema_editor):     # We can't import the Person model directly as it may be a newer     # version than this migration expects. We use the historical version.     Person = apps.get_model("yourappname", "Person")     for person in Person.objects.all():         person.name = "%s %s" % (person.first_name, person.last_name)         person.save()  class Migration(migrations.Migration):     initial = True      dependencies = [         ('yourappname', '0001_initial'),     ]      operations = [         migrations.RunPython(combine_names),     ] 
like image 100
durdenk Avatar answered Sep 18 '22 17:09

durdenk