Django Road: QuerySet API, Background and forms

Source: Internet
Author: User

One, Django QuerySet API

In the Django model we learned some basic creation and query. Here are the following database interface related interfaces (QuerySet API), of course, you can also choose to temporarily skip this section. If you use the database later, you can also look at it.

The result of querying from the database is generally a collection, which is called Queryset.

Most of the examples in this article are based on this blog/models.py

From django.db import Models  class Blog (models. Model):    name = models. Charfield (max_length=100)    tagline = models. TextField ()     def __unicode__ (self):  # __str__ on Python 3        return Self.name class Author (models. Model):    name = models. Charfield (max_length=50)    email = models. Emailfield ()     def __unicode__ (self):  # __str__ on Python 3        return Self.name class Entry (models. Model):    blog = models. ForeignKey (Blog)    headline = models. Charfield (max_length=255)    Body_text = models. TextField ()    pub_date = models. Datefield ()    mod_date = models. Datefield ()    authors = models. Manytomanyfield (Author)    n_comments = models. Integerfield ()    n_pingbacks = models. Integerfield ()    rating = models. Integerfield ()     def __unicode__ (self):  # __str__ on Python 3        return Self.headline

1. QuerySet Methods for creating objects

>>> from blog.models import blog>>> b = blog (name= ' Beatles blog ', tagline= ' all the latest Beatles news. ') ) >>> B.save () in short, a total of four ways # method 1author.objects.create (name= "Wulaoer", email= "[email protected]") # Method 2TWZ = Autho R (name= "Wulaoer", email= "[email protected]") Twz.save () # Method 3twz = Author () twz.name= "Wulaoer" twz.email= "[email Protected] "# Method 4, first try to get, does not exist on creation, can prevent duplicate Author.objects.get_or_create (name=" Wulaoer ", email=" [email protected] ") # return value ( Object, True/false)

Note: The first three methods return the corresponding object, and the last method returns a tuple, (Object,true/false), which returns True when it is created, and returns False when it already exists.

When there is a pair, many to one, or many-to-many relationships, first query the relevant objects

>>> from blog.models import entry>>> Entry = Entry.objects.get (pk=1) >>> Cheese_blog = Blog.objects.get (name= "Cheddar talk") >>> Entry.blog = cheese_blog>>> Entry.save ()

2. How to get the object (part of the code in the previous article)

Person.objects.all () # Query all Person.objects.all () [: 10] slicing operation, get 10 people, do not support negative index, slice can save memory, do not support negative index, there are corresponding solutions, 7th Person.objects.get (name= "Wulaoer") # is the name of a wulaoer, a number of errors get is used to get an object, if you need to get the conditions of some people, To use FilterPerson.objects.filter (name= "abc") # Equals Person.objects.filter (name__exact= "abc") name Strictly equals "abc" The person Person.objects.filter (name__iexact= "abc") # NAME is ABC but not case-sensitive, you can find ABC, ABC, ABC, these all meet the conditions Person.objects.filter (name__ contains= "abc") # NAME contains "ABC" Person Person.objects.filter (name__icontains= "abc") #名称中包含 "ABC", and ABC is case insensitive Person.objects.filter (name__regex= "^ABC") # Regular expression query Person.objects.filter (name__iregex= "^ABC") # Regular expressions are case-insensitive # Filter is found to meet the conditions, of course, there are also excluded Person.objects.exclude (name__contains= "wz") # Exclude the Person object containing WZ Person.objects.filter ( name__contains= "ABC"). Exclude (AGE=23) # Find out the name contains ABC, but the exclusion age is 23 years old

3, Queryset is iterative, such as:

es = Entry.objects.all () for E in es:    print (E.headline)

Entry.objects.all () or ES is Queryset is a query for all Entry entries.

Precautions:

(1), if only to check whether there are objects in entry, you should use Entry.objects.all (). Exists ()

(2),

  

Django Road: QuerySet API, Background and forms

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.