Django's model uses ORM to operate the database. Generally, we only need to pay attention to the model class itself, and Django will handle the ing to the database. But there are always exceptions, and sometimes the default ing behavior needs to be changed. Django also provides rich support for this.
1. Custom Field name
The default field name is the same as the attribute name, which can be customized using the db_column attribute of the field, as shown in
Where = models. charfield (max_length = 400, db_column = 'place ')
2. Custom Index
Except the ID field, other fields are not indexed by default. You can use the db_index attribute of the field to customize the index. For example:
Publish_date = models. datefield (db_index = true)
3. Custom ID
If no ID is specified, an ID field of integerfield type is created by default. You can specify your ID field through the primary_key attribute of the field. For example:
Key = models. integerfield (primary_key = true)
4. Custom table name
The default table name is appname_modelname. In the meta of the model class, you can use the db_table attribute to change the default table name.
5. Custom tablespace
For index fields, indexes are created in the tablespace set by settings ult_index_tablespace in settings by default. You can specify indexes by specifying the db_tablespace attribute of the field, as shown in figure
Publish_date = models. datefield (db_index = true, db_tablespace = 'another _ TBS ')
For the model class, use the db_tablespace attribute in Meta to specify a specific tablespace.
6. Custom associations
1) The foreign key is associated with the primary key field of the other party by default. You can use to_field of the foreign key to specify the associated field, as shown in figure
To_model = models. foreighkey (tomodel, to_field = 'key ')
2) for association between tables-to-tables, Django creates an association table. By default, the table names are connected by underscores. You can use db_table of manytomanyfield to specify the table name of the associated table. 3) If you do not want to use the join table created by Django for external-to-External Association, you can use the through attribute of manytomanyfield to specify an existing model class.