Django - ORM using a recording (II)

ORM query
  • queryset objects and objects
    • 1.queryset query set is reached inside the url content on the server. Django will result sets returned by the query cache QerySet here is to improve query efficiency, that is, you create a QuerySet object when, Django will not immediately issue a query command to the database, only if you need to use this QuerySet time to go back a database query
    • 2.Objects django mvc framework data layer implemented in the (model) m, the model has a class django objects in the object, which is the object of a django QuerySet type defined which contains a model of the object instance. Simply put, objects are single objects, queryset are many objects
    • 3.QuerySet can be constructed, filtered, sliced, passed as a parameter, these acts do not have to operate the database. As long as when you query the database only real operating
Manager Methods Return Type Explanation
Model class .objects.all () QuerySet Returns all data in
filter() QuerySet Returns the qualified data
values() ValuesQuerySet (QuerySet subclass) Returns a list of each element is a dictionary
values_list() ValuesListQuerySet (QuerySet subclass) Returns a list of elements but it is not a dictionary, but a tuple
get() Object Model Return an object to satisfy the conditions; if they meet the conditions of the object is not found, would lead to a model class .DoesNotExist abnormal; if more is found, can cause abnormal model class .MultiObjectsReturned
first() Object Model Return the first data
last() Object Model Returns the last piece of data
exclude() QuerySet Returns qualified data
order_by() QuerySet The query result set to sort
reverse() QuerySet The results of the sort of reversal
count() int Returns the number of objects in the query
exists() bool Query whether the data to determine the existence of
  • 1.len () and count ()

    • The number of computing elements QuerySet, not recommended len (), unless QuerySet is begged value (that is evaluated), otherwise, with QuerySet.count () Gets the number of elements, the efficiency is much higher, especially in large volumes of data ( thousands) time
  • 2.if QuerySet: 与 if QuerySet.exists()

    • Also we do not recommend if QuerySetthis method to determine whether the air, but you should use QuerySet.exists (), high query efficiency
  • 3.F class

from django.db import models
from django.db.models import F

class User(models.Model):
    name = models.CharField(max_length=10)
    age = models.IntegerField()
    both = models.CharField(max_length=20)

Do not use F ()

s = User.objects.get(name='xxx')
s.age += 1
s.save()

Object search from the database into memory, and then counted and then stored in the database

Use F ()

s = User.objects.get(name='xxx')
s.age = F('age') + 1
s.save()

Identify data directly in the database, change the database after count

    1. Class Q - corresponds to (and / or / not)
    • If there is a logical relationship or waiting for, then use the Q class
    • The filter condition can be the object Q and non-Q query mixed use, but this is not recommended, because when mixed query Q to put in front of the object, so there will inevitably forget the order and error, so if you use Q objects, it is all in Q objects
    • Q objects is also very simple, it is the original filter in each condition were placed in a Q () can be, but we can also use or non, corresponding symbol "|" and "&" and "~", and these logical operation returns the object or one Q, further, the comma is the basic condition of the connector of each group, and the relationship is, in fact, may be used instead of & (tested in python manage.py shell, instead of & comma, the SQL execution is the same), but in that case will be poor readability, this time to write SQL directly with us, and when each set of conditions with line breaks, like, clear logic
>>> python manage.py shell
>>> from django.db.models import Q
>>> Poll.objects.get( Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6)),
question__startswith='Who')   # 正确,但不要这样混用
>>> Poll.objects.get( Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6)),
Q(question__startswith='Who'))  # 推荐,全部是Q对象
>>> Poll.objects.get( (Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6)))&
Q(question__startswith='Who'))  # 与上面语句同意,&代替”,”,可读性差

F class should be able to use it when the class Q ?? are interested can try

  • annotate (with no corresponding SQL keywords)
    • Function annotate(*args, **kwargs): return QuerySet
    • QuerySet to each model instance is added one or more fields, field values ​​are only aggregation function is used, since Annotate, will use group by, polymerization can only function. Can function as a polymerization association table as filter, i.e., in an aggregate function, Django for OneToOne, OneToMany, ManyToMany relational query and inversely related to the same manner as provided

Example:

from django.db.models import Count
s = User.objects.all().annotate(n=Count('age'))
  • 5.order_by()

    • If the field name directly, that is arranged in ascending asc; if the first field names - is descending desc
    • Return QuerySet
  • 6.distinct()

    • General and values ​​(), values_list () used in conjunction, then it returns ValuesQuerySet, ValuesListQuerySet This class is very similar with the list, which each element is a dictionary
    • It is no argument (in fact, there are parameters, but the parameters only work on PostgreSQL)
      Example:
s = User.objects.values('name').distinct()
  • 7.aggregate
    • aggregate(*args,**kwargs): Parameter is a function of the polymerization, is preferably used **kwargsin the form of, for each parameter from a name
    • Aggregate annotate equivalent binding () and group_by of each group performs Aggregate () function. While a separate Aggregate () does not group_by
from django.db.models import Count
# 这是用*args的形式,最好不要这样用
s = User.objects.aggregate(Count('name'))
# 这是用**kwargs的形式
s = User.objects.aggregate(n=Count('name'))
  • 8. Fuzzy query

    • gt/gte/lt/lteCorrespondence >,>=,<,<=: double underlined field name
      • age__gt=18: Older than 18
    • inCorrespondence in: double underlined field name
    • contains/startswith/endswithCorrespondence like: double underlined field name
    • rangeCorrespondence between and: double underlined field names, range after a par value list
    1. extra()
    • extra(select=None, where=None, params=None, tables=None, order_by=None, select_params=None)
    • Implement complex where the words, may specify one or more parameters params Extra, such as select, where or tables. All parameters are optional, but at least you want to use a
      simple example:
s = User.objects.extra(select={'is_recent':"both>'2000-01-01'"})s

Reproduced in: https: //www.jianshu.com/p/80a6e504c11a

Guess you like

Origin blog.csdn.net/weixin_33851429/article/details/91182298