Django Database Operation __ Database

Source: Internet
Author: User
Tags datetime

1. Add Field

From django.db import Models
class person (models. Model):
    name = models. Charfield (max_length=30) Age
    = models. Integerfield ()
    def __str__ (self): return
        Self.name

2. Creating objects
1). Person.objects.create (name= "John", age=89)
2). P = person (name= "Dick", age=23)
P.save ()
3). P = person (name= "Harry")
P.age = 56
P.save ()
4). Person.objects.get_or_create (name= "Xiao Liu", age=34)
This method is relatively slow, but checks for duplicates, returns a tuple, the first person object, and the second is true (new)/false (already exists)

3. Get objects
1). Person.objects.all ()
2). Person.objects.get (name= "abc") #等于3
3). Person.objects.filter (name__exact= "abc") #名称严格等于 "abc" person
4). Person.objects.filter (name__iexact= "abc") name is ABC case-insensitive
5). Person.objects.filter (name__contains= "abc") contains "ABC"
6). Person.objects.filter (name__icontains= "abc") does not contain
7). Person.objects.filter (name__regex= "^abc") Regular expression
8). Person.objects.filter (name__iregex= "abc") are not case-sensitive
9). Person.objects.exclude (name__contains= "abc") #排除包含abc的对象
10). Person.objects.filter (name__icontains= "ABC"). Exclude (AGE_CONTAINS=23) #名称中含有abc age is not equal to 23

4. Modify Data
1). Someone = Person.objects.get (name= "abc")
Someone.age = 25
Someone.save ()
1). Someone = Person.objects.get (name= "abc")
Someone.update (name= "CBA", age=25)

5. Delete data
1). Person.objects.all (). Delete ()
2). Person.objects.get (name= "abc"). Delete ()

6. Data Bulk Import
Import text adress_book.txt, which reads as follows:
Lion***35
Rabbit***36
Import Script djangodb.py

Import OS
os.environ.setdefault ("Django_settings_module", "mysite.settings")

import DJANGO
# The Django version is greater than 1.7 to add the following two lines
if Django. VERSION >= (1,7):
    Django.setup ()

def Main (): from
    . Models Import person
    f = open (' Djangodb.txt ') For line in
    f:
        name,age = Line.split (' * * *)
        Person.objects.create (name=name,age=age)
    f.close ()

if __name__ = = "__main__":
    main ()
    print ("done!")

7.model.objects.bulk_create () Import method

#main代码处不同
def Main (): from
    . Models Import person
    f = open (' Djangodb.txt ')
    personlist = []
    For line in F:
        name,age = Line.split (' * * *) person
        = person (name=name,age=age)
        personlist.append ( person)
    F.close ()
    Person.objects.bulk_create (personlist)

8. Next reprint from http://blog.sina.com.cn/s/blog_611f501001015vm8.html
relatively full, more practical
Python code

    Class Blog (models. Model):   
         name = models. Charfield (max_length=100)   
         tagline = models. TextField ()   

        def __unicode__ (self): return   
            Self.name   

    class Author (models. Model):   
         name = models. Charfield (max_length=50)   
         email = models. Emailfield ()   

        def __unicode__ (self): return   
            Self.name   

    class Entry (models. Model):   
         blog = models. ForeignKey (Blog)   
         headline = models. Charfield (max_length=255)   
         Body_text = models. TextField ()   
         pub_date = models. Datetimefield ()   
         authors = models. Manytomanyfield (Author)   

        def __unicode__ (self): return   
            Self.headline  

This is model, there are blog,author, as well as entry, which entry respectively with the blog and Author Table Association, entry and blog table is through the foreign key (models. ForeignKey ()) connected, belong to a one-to-many relationship, that is, a entry corresponding to multiple blog,entry and author is a many-to-many relationship through Modles. Manytomanyfield () implementation.
First, insert the database and use the Save () method to implement the following:

>>> from mysite.blog.models Import blog
>>> b = blog (name= ' Beatles blog ', tagline= ' all the latest to be Atles news. ')
>>> B.save ()

Second, update the database, also use the Save () method to implement, as follows:

>> b5.name = ' New name '
>> b5.save ()

A field that holds a foreign key and a many-to-many relationship, as in the following example:
Update the Foreign key field and the normal field as long as you specify the correct type of an object.

>>> Cheese_blog = Blog.objects.get (name= "Cheddar Talk")
>>> entry.blog = Cheese_blog
> >> Entry.save ()

Updating a many-to-many field is a bit different, using the Add () method to add the value of the associated field.

>> Joe = Author.objects.create (name= "Joe")
>> Entry.authors.add (Joe)

Third, retrieve the object

>>> blog.objects
<django.db.models.manager.manager object at ...>
>>> b = Blog (name= ' Foo ', tagline= ' Bar ')
>>> b.objects
traceback:
    ...
Attributeerror: "Manager isn ' t accessible via Blog instances."

1, retrieve all the objects

>>> all_entries = Entry.objects.all ()

Use the All () method to return all objects in the database.

2. Retrieving specific objects
Use the following two methods:
Fileter (**kwargs)
Returns a queryset that matches a parameter equal to (=).
Exclude (**kwargs)
Returns a queryset that does not match the parameter, equivalent to not equal to (!=).

Entry.objects.filter (pub_date__year=2006)
Do not use Entry.objects.all (). Filter (pub_date__year=2006), although it can also be run, all () is best to use when retrieving all objects.
The above example is equivalent to the SQL statement:
Slect * from entry where pub_date_year= ' 2006 '

Link filter:

>>> Entry.objects.filter (
....     .) Headline__startswith= ' What ' ...
). Exclude (
...     ..) Pub_date__gte=datetime.now () ...
). Filter (
...     ..) Pub_date__gte=datetime (1, 1)
...)

The last Queryset returned was headline like ' what% ' and put_date

>> q1 = Entry.objects.filter (headline__startswith= "What")
>> q2 = q1.exclude (pub_date__gte= DateTime.Now ())
>> q3 = Q1.filter (Pub_date__gte=datetime.now ())

The advantage of this approach is that it can be reused for Q1.

Queryset is deferred loading
Access to the database is available only at the time of use, as follows:

>>> q = Entry.objects.filter (headline__startswith= "What")
>>> q = q.filter (pub_date__lte= DateTime.Now ())
>>> q = q.exclude (body_text__icontains= "food")
>>> print Q

The database is not accessed until print Q.

Other methods of Queryset

>>> Entry.objects.all () [: 5]

This is the data for the first 5 entry.

>>> Entry.objects.all () [5:10]

This is the data to find between 5th and 10th.

>>> Entry.objects.all () [: 10:2]

This is the query from the No. 0 start to the 10th, the step is 2 data.

>>> Entry.objects.order_by (' headline ') [0]

This is the first object that is sorted by pressing the headline field.

>>> Entry.objects.order_by (' headline ') [0:1].get ()

This is equivalent to the above.

>>> Entry.objects.filter (pub_date__lte= ' 2006-01-01 ')

Equivalent to select * from Blog_entry WHERE pub_date <= ' 2006-01-01 ';

>>> Entry.objects.get (headline__exact= "Man Bites Dog")

Equal to select ... WHERE headline = ' Man Bites dog ';

>>> Blog.objects.get (id__exact=14) # Explicit form
>>> Blog.objects.get (id=14)         # __exact is Implied

The two methods are equivalent, both of which are looking for id=14 objects.

>>> Blog.objects.get (name__iexact= "Beatles Blog")

Find Name= "Beatles Blog" object, do not go to the case of rice.

Entry.objects.get (headline__contains= ' Lennon ')

Equal to select ... WHERE headline like '%lennon% ';

StartsWith is equivalent to the name like ' lennon% ' in the SQL statement,
EndsWith is equivalent to the name like '%lennon ' in the SQL statement.

>>> Entry.objects.filter (blog__name__exact= ' Beatles blog ')

Find Entry table foreign key relationship blog_name= ' Beatles Blog ' entry object.

>>> Blog.objects.filter (entry__headline__contains= ' Lennon ')

Find the Blog Table foreign key relationship entry the headline field in the table contains the Lennon blog data.

Blog.objects.filter (entry__author__name= ' Lennon ')
Find the Blog Table foreign key relationship entry the Author field in the table contains the Lennon blog data.

Blog.objects.filter (Entry__author__name__isnull=true)
Blog.objects.filter (Entry__author__isnull=false,entry__author__name__isnull=true)
The query is a value that is author_name null

Blog.objects.filter (entry__headline__contains= ' Lennon ', entry__pub_date__year=2008)
Blog.objects.filter (entry__headline__contains= ' Lennon '). Filter (entry__pub_date__year=2008)
These two queries are the same in some cases and are different in some cases. The first is to restrict all blog data, and the second is the first filter is
Limit the blog, while the second filter is restricted entry

>>> Blog.objects.get (id__exact=14) # Explicit form
>>> Blog.objects.get (id=14) # __exact is Implied
>>> Blog.objects.get (pk=14) # PK implies id__exact

Equivalent to select * from where id=14

# Get blogs entries with ID 1, 4 and 7
>>> Blog.objects.filter (pk__in=[1,4,7])

Equivalent to select * from where ID in{1,4,7}

# Get all blogs entries with ID >
>>> Blog.objects.filter (pk__gt=14)

Equivalent to select * from id>14

>>> Entry.objects.filter (blog__id__exact=3) # Explicit form
>>> Entry.objects.filter (blog__id =3)        # __exact is implied
>>> Entry.objects.filter (blog__pk=3)        # __PK implies __id__exact

These three kinds of cases are the same

>>> Entry.objects.filter (headline__contains= '% ')

Equal to select ... WHERE headline like '%\%%

Caching and querys>>> Print [E.headline for E in Entry.objects.all ()]
>>> Print [e.pub_date to E in Entry.objects.all ()] is:
>> queryset = Poll.objects.all ()
>>> Print [P.headline for P in Queryset] # Evaluate the query set.
>>> Print [P.pub_date for P in Queryset] # Re-use The cache from the evaluation.

This uses caching to reduce the number of accesses to the database.

Implementation of complex queries with Q-Object

Q (question__startswith= ' Who ') | Q (question__startswith= ' What ')

Equivalent to where question like ' who% ' OR question like ' what% '

Poll.objects.get (
    Q (question__startswith= ' who '),
    Q (Pub_date=date (2005, 5, 2)) | Q (Pub_date=date (5, 6))

Equivalent to select * from polls WHERE question like ' who% ' and (pub_date = ' 2005-05-02 ' OR pub_date = ' 2005-05-06 ')

Poll.objects.get (
    Q (Pub_date=date (2005, 5, 2)) | Q (Pub_date=date (5, 6)),
    question__startswith= ' who '

Equivalent to Poll.objects.get (Question__startswith= ' Who ', Q (Pub_date=date (2005, 5, 2)) | Q (Pub_date=date (2005, 5, 6))

V. Comparison of objects

>>> Some_entry = = Other_entry
>>> some_entry.id = = Other_entry.id

Vi. deletion

Entry.objects.filter (pub_date__year=2005). Delete ()

B = Blog.objects.get (pk=1)
# This'll deletes the Blog and All of its Entry objects.
B.delete ()

Entry.objects.all (). Delete ()

七、一次 Update Multiple values

# Update All of the headlines with Pub_date in 2007.
Entry.objects.filter (pub_date__year=2007). Update (headline= ' Everything is the same ')

>>> b = Blog.objects.get (pk=1)
# change every Entry the it belongs to this Blog.
>>> Entry.objects.all (). Update (BLOG=B)

If you use the Save () method, you must save one at a, and you need to iterate over it, as follows:
For item in My_queryset:
Item.Save ()

Associating objects

One-to-many

>>> e = Entry.objects.get (id=2) >>> E.blog # Returns the related blog object. >>> e = Entry.objects.get (id=2) >>> e.blog = Some_blog >>> e.save () >>> e = Entry.obj

Ects.get (id=2) >>> e.blog = None >>> e.save () # "UPDATE blog_entry SET blog_id = NULL ...;"
>>> e = Entry.objects.get (id=2) >>> Print E.blog # Hits The database to retrieve the associated blog. >>> Print E.blog # doesn ' t hit the database;

Uses cached version. >>> e = Entry.objects.select_related (). Get (id=2) >>> print E.blog # doesn ' t hit the database;
Uses cached version. >>> Print E.blog # doesn ' t hit the database; Uses cached version >>> B = Blog.objects.get (id=1) >>> B.entry_set.all () # Returns all entry objects re

lated to Blog.
# B.entry_set is a Manager that returns querysets. >>> b.entry_set.filter (headline__contains= ' Lennon ') >>> B.entry_set.count () &Gt;>> B = Blog.objects.get (id=1) >>> B.entries.all () # Returns all Entry objects to Blog.
# b.entries is a Manager that returns querysets. >>> b.entries.filter (headline__contains= ' Lennon ') >>> B.entries.count ()

Cannot access a reverse ForeignKey Manager from the class; It must be accessed from the instance:

>>> Blog.entry_set

Add (Obj1, Obj2, ...)
Adds the specified model objects to the related object set.
Create (**kwargs)
Creates a new object, saves it and puts it in the related object set. Returns the newly created object.
Remove (obj1, obj2, ...)
Removes the specified model objects from the related object set.
Clear ()
Removes all objects from the related object set.

Many-to-many Type:

E = Entry.objects.get (id=3)
E.authors.all () # Returns all Author objects for this Entry.
E.authors.count ()
e.authors.filter (name__contains= ' John ')
a = Author.objects.get (id=5)
A.entry_ Set.all () # Returns all Entry objects to this Author.

One-to-one type:

Class Entrydetail (models. Model):
    entry = models. Onetoonefield (Entry)
    details = models. TextField ()

ed = EntryDetail.objects.get (id=2)
Ed.entry # Returns The related entry object

To query using SQL statements:

def my_custom_sql (self): from
    django.db import connection
    cursor = connection.cursor ()
    cursor.execute (" SELECT foo from bar WHERE baz =%s ', [Self.baz]]
    row = Cursor.fetchone () return
    row

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.