Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Default value in Database, not just ORM

I would like to have a default value for a column in the database, not just the django orm.

Related ticket is in state "wontfix": https://code.djangoproject.com/ticket/470

What is the preferred way to create a default value in the relational database?

In my case it is a BooleanField which should default to FALSE.

I use PostgreSQL, but AFAIK this should not matter in this context.

like image 254
guettli Avatar asked Aug 13 '15 11:08

guettli


People also ask

Is Django ORM a database?

One of the most powerful features of Django is its Object-Relational Mapper (ORM), which enables you to interact with your database, like you would with SQL. In fact, Django's ORM is just a pythonical way to create SQL to query and manipulate your database and get results in a pythonic fashion.

Is Django ORM good?

The Django ORM is a very powerful tool, and one of the great attractions of Django. It makes writing simple queries trivial, and does a great job of abstracting away the database layer in your application. And sometimes, you shouldn't use it.

What is default Django?

default: The default value for the field. This can be a value or a callable object, in which case the object will be called every time a new record is created. null: If True , Django will store blank values as NULL in the database for fields where this is appropriate (a CharField will instead store an empty string).

What is Django ORM called?

Django ORM provides an elegant and powerful way to interact with the database. ORM stands for Object Relational Mapper. It is just a fancy word describing how to access the data stored in the database in Object Oriented fashion. Start Django shell using the shell command.


1 Answers

I solved it like this. The file was created with manage.py makemigrations. I added only the line at the bottom.

class Migration(migrations.Migration):

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='State',
            fields=[
                ('id', models.CharField(max_length=256, serialize=False, primary_key=True)),
                ('state', models.BooleanField(default=True)),
            ],
            bases=(models.Model,),
        ),

        ### The following line was added 
        migrations.RunSQL('alter table box_state alter column state set default false')
    ]
like image 134
guettli Avatar answered Sep 28 '22 09:09

guettli