From django.db Import models Class TableName (models. Model): name = models. Charfield (max_length=30) Age = models. Integerfield () date = models. Datefield () def __unicode__ (self): #__str__ python3.x return Self.name class Meta: #不加Meta类的话 with the table named " Appname_tablename ", TableName db_table =" TableName "#一个 the name of the Datefield or Datetimefield field, as indicated in the following addition . If this option is available, The module will have a #get_latest () function to get the "most recent" object (depending on that field): get_latest_by = "Date"
Use MySQL. Modify the settings in setting.py
Enter MySQL new database MySite (corresponding name)
Then in the project directory
>>>python manage.py makemigrations
>>>python manage.py Migrate
Synchronize database, automatically create TABLE tablename
After modifying the database, you should also synchronize the database as above
Modifications to the database:
(1) operation at the terminal
>>>python manege.py Shell
>>>from app_name.models Import TableName
>>>tablename.objects.create (name= ' name ', age=age,date= ' yyyy-mm-dd ')
(2) Add TableName.objects.create (name= ' name ', age=age,date= ' yyyy-mm-dd ') into the file.
(3) Execute MySQL statement directly
Django.db.connection: Represents the default database connection
Django.db.transaction: Represents the default database transaction (transaction)
Call Connection.cursor () with database connection to get a cursor object.
Then call cursor.execute (SQL, [params]) to execute the SQL
Cursor.fetchone () or cursor.fetchall (): Returns the result row
If you perform a modify operation, call transaction.commit_unless_managed () to ensure that your changes are committed to the database.
Def my_custom_sql (): From django.db import connection, transaction cursor = Connection.cursor () # Data modification operation-- Submit Request Cursor.execute ("UPDATE bar SET foo = 1 WHERE baz =%s", [Self.baz]) transaction.commit_unless_managed () # Data retrieval operation, no need to commit cursor.execute ("select Foo from bar WHERE baz =%s", [Self.baz]) row = Cursor.fetchone () Return row
Django Model Models