Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django DB level default value for a column

Django is proving the model field argument default (https://docs.djangoproject.com/en/dev/ref/models/fields/#default) but as I know it will be called every time new object is created via django. If we insert/create a records with raw queries (using django.db.connection.cursor) we will get the exception cause Field 'xyz' doesn't have a default value.

How to represent the db level default value for the column in model. Like db_index.

I hope you guy understand my question.

like image 304
neotam Avatar asked Sep 07 '14 18:09

neotam


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.

What is the default value of column for which no default value is defined?

If a data type specification includes no explicit DEFAULT value, MySQL determines the default value as follows: If the column can take NULL as a value, the column is defined with an explicit DEFAULT NULL clause. If the column cannot take NULL as a value, MySQL defines the column with no explicit DEFAULT clause.

Why would you use default values in columns?

A default value makes it a lot easier to insert new rows into a table - all columns with a default value do not need to be explicitly specified and provided with a value in the INSERT statement, if that default value is OK (like getdate() for a "LastChangeOn" date column).

Are Django fields nullable by default?

Default is False." Look at the next paragraph: Avoid using null on string-based fields such as CharField and TextField because empty string values will always be stored as empty strings, not as NULL. If a string-based field has null=True, that means it has two possible values for “no data”: NULL, and the empty string.


1 Answers

There is an open ticket 470 to include default values in the SQL schema.

Until this feature has been added to Django, you'll have to manually run alter table statements yourself or write a migration to run them if you want a default value in the SQL schema.

Note that Django allows callables as defaults, so even if this feature is added to Django, it won't be possible to have all defaults in the database.

like image 122
Alasdair Avatar answered Sep 27 '22 20:09

Alasdair