Directory:
1. Configure the Access database
In the settings.py file, add:
DATABASES = {
' Default ': {
# ' ENGINE ': ' Django.db.backends.sqlite3 ',
# ' NAME ': Os.path.join (Base_dir, ' db.sqlite3 '),
' ENGINE ': ' Django.db.backends.postgresql_psycopg2 ',
' NAME ': ' AA ',
' USER ': ' Postgres ',
' PASSWORD ': ' Root ',
' HOST ': ',
' PORT ': ',
}
}
2.python Original Access database:
#-*-coding:utf-' 8 ' "-*-"
# python original used linked database
From django.db Import Connection
# Cursors
cursor = Connection.cursor
#执行sql语句
Cursor.execute (' select * from Django_migrations ')
# Get return value
result = Cursor.fetchall ()
# Close Cursors
Cursor.close ()
3. The new creation table, which is the creation of the Django Class (models):
Add the class MySite in the models.py file as follows:
From django.db import Models
Class Mysite (models. Model):
title = models. Charfield (max_length=100)
URL = models. Urlfield ()
Author = models. Charfield (max_length=100)
num = models. Charfield (max_length=10)
# sort
Class Meta:
ordering = [' num ']
Some things to see on the command line:
# Verify that SQL is correct (that is, the variable (field) created by the class MySite is correct):D: \django_project\project_study_1\myproject>python manage.py Validate
# View the SQL statement for (that is, the SQL statement for Class MySite):D: \django_project\project_study_1\myproject>python manage.py sqlall MyProject
#同步到数据库 (that is, the table for which you created the class MySite (table named Mytest_mysite):D: \django_project\project_study_1\myproject>python manage.py syncdb
2. Add, insert data:
1. Querying all data
From mytest.models Import *
m = Mysite.object.all ()
Access to fields via M[0].title when there is data
2. Add Data
M=mysite (title= ' Django ', num= ' 2 ')
M.save ()
3. Querying for objects (num is ' 2 ')
M=mysite.objects.get (num= ' 2 ')
Gets the value of the title
M.title
4. Sorting (sorted by num ascending order)
M=mysite.objects.all (). order_by (' num ')
(sorted by num descending order)
M=mysite.objects.all (). order_by ('-num ')
3. Update and delete:
5. Updating data
M=mysite.objects.get (num= ' 2 ')
m.title= ' python '
M.save ()
View data
M=mysite.objects.get (num= ' 2 ')
M.title
6. Delete data
M=mysite.objects.get (num= ' 2 ')
M.delete ()
7. Get the number of results for the query
M=mysite.objects.all () [: 2]
Django's PostgreSQL access