Python Django Database Operations

Source: Internet
Author: User

1. Create an App

In your project directory, enter:

Python manage.py Startapp MyApp (the app name you want to build)

Create an app called MyApp

In this way, a directory called MyApp will appear in your project directory.

2. Create model

Enter models.py in the app directory

Enter code similar to the following:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

classPublisher(models.Model):

    name =models.CharField(max_length=30)

    address =models.CharField(max_length=50)

    city =models.CharField(max_length=60)

    state_province =models.CharField(max_length=30)

    country =models.CharField(max_length=50)

    website =models.URLField()

classAuthor(models.Model):

    first_name =models.CharField(max_length=30)

    last_name =models.CharField(max_length=40)

    email =models.EmailField()

classBook(models.Model):

    title =models.CharField(max_length=100)

    authors =models.ManyToManyField(Author)

    publisher =models.ForeignKey(Publisher)

    publication_date =models.DateField()

Each class above is equivalent to a new table

Exception is many to many relationship

(Note: The exception to the one-class-per-database-table rule was the case ofmany-to-many relationships. In we example models, book have amanytomanyfield called authors. This designates is a book with one Ormany authors, but the Book database table doesn ' t get a authorsCol Umn. Rather, Django creates an additional table–a Many-to-many "jointable" –that handles the mapping of books to authors.)

Django automatically configures each model with a primary key named ID

(Finally, note we haven ' t explicitly defined a primary key in any of thesemodels. Unless instruct it otherwise, Django automatically gives Everymodel an auto-incrementing integer primary key field cal LED ID. Each djangomodel are required to a Single-column primary key.)

3. Install model

Found in the initial configuration file settings.py

Installed_apps

Add your own app name, such as ' MyApp '

Verify the validity of the model with the following command:

Python manage.py Validate

If everything is OK, you will see the 0errorsfound message. If an error occurs, check the model code you entered. The error output will give you a very useful error message to help you fix your model. Once you feel your model may be having problems, run pythonmanage.pyvalidate . It can help you catch some common model definition errors.

4. (Really create the table we set up in db) CREATE TABLE:

In the shell, enter

Python manage.py sqlall MyApp (the app name you created in step 1)

Then you can see the various SQL statements, well, it looks good. But...... "Thesqlall command does not actually create the data table in the database, just print out the SQL statements, so you can see what Django is going to do." ”

So here's the statement that really builds the table:

Python manage.py syncdb

You should then be able to see such things as:

Creating tables ...
Creating Table Books_publisher
Creating Table Books_author
Creating Table Books_book_authors
Creating Table Books_book
Installing Custom SQL ...
Installing indexes ...
Installed 0 object (s) from 0 fixture (s)

Such a message

It is important to note that thesyncdb command is an easy way to synchronize your model to the database. It checks the database based on the app set in Installed_apps and creates it if the table doesn't exist. It is important to note that syncdb does not synchronize the modification or deletion of the model to the database; If you modify or delete a model and want to commit it to the database,syncdb does not make any processing.

5. (Insert a new object) insert:

>>> from books.models import publisher>>> p1 = Publisher (name= ' Apress ', address= ' 2855 Telegraph Avenue ',...     City= ' Berkeley ', state_province= ' CA ', country= ' U.S.A. ',...     Website= ' http://www.apress.com/') >>> P1.save ()

View:

>>> publisher_list = Publisher.objects.all ()

>>> publisher_list

6. Additional questions: Adding a string representation to the model

In each model, add:

1

2

def__unicode__(self):

    returnself.name

Write the string you want at return

7. (select Object) Select:

Publisher.objects.all ()

--equivalent to select from

Publisher.objects.filter (name= ' Apress ')

--equivalent to select from ... where name = ' Apress '

Publisher.objects.filter (name__contains= "Press")

-equivalent to select from ... where name like '%press% ';

The above method, return is a list (in fact, query set)

Want to get a single object directly? With the Get Method!

Publisher.objects.get (name= "Apress")

8. (Sort results) Order:

Publisher.objects.order_by ("name")

-equivalent to select from ... ORDER by name;

Multi-Item Ordering:

Publisher.objects.order_by ("State_province", "address")

Reverse order:

Publisher.objects.order_by ("-name")

Chain query:

Publisher.objects.filter (country= "U.S.A."). Order_by ("-name")

9. (Update object) Update:

1) Use the Save () method:

1

2

3

>>> p =Publisher.objects.get(name=‘Apress‘)

>>> p.name =‘Apress Publishing‘

>>> p.save()

--equivalent

1

2

3

4

5

6

7

8

UPDATEbooks_publisher SET

    name‘Apress Publishing‘,

    address = ‘2855 Telegraph Ave.‘,

    city = ‘Berkeley‘,

    state_province = ‘CA‘,

    country = ‘U.S.A.‘,

    website = ‘http://www.apress.com‘

WHEREid = 52;

!! All the columns have been updated! This is too naive!

2) It's better to use the update () method:

Publisher.objects.filter (id=52). Update (name= ' Apress publishing ')

--equivalent

1

2

3

UPDATEbooks_publisher

SETname‘Apress Publishing‘

WHEREid = 52;

You can update multiple lines at the same time:

Publisher.objects.all (). Update (country= ' USA ')

The update () method returns an integer value that represents the number of affected record bars

10. (Delete object) Delete: Call the object's Delete () method:

p = Publisher.objects.get (name= "O ' Reilly")

P.delete ()

Once the All () method is used, all data will be deleted:

Publisher.objects.all (). Delete ()

Reference: http://www.djangobook.com/en/2.0/chapter05.html

http://djangobook.py3k.cn/2.0/chapter05/

Python Django Database Operations

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.