Django's query Q query F

class Class(models.Model):

"" "Class Table" ""

class_name = models.IntegerField () # class name

class_grade = models.IntegerField () # class young

boy_num = models.IntegerField () # number of boys

girl_num = models.IntegerField () # The number of girls

""""""""""""""""""""""""""""""""""""""""""""""""""""""""

from django.db.models import Q,F

""""""""""""""""""""""""""""""""""""""""""""""""""""""""

In Django F queries may refer to other fields of the same model in the query.

Class.objects.filter (boy_num__ge = F ( 'girl_num')) for screening class boys than girls

F can help us get to the table a field corresponding values ​​as my filter criteria, rather than custom constant conditions, and to achieve a dynamic comparative results

Django supports F (, and () operation between the object and the addition, subtraction modulo F constant and between objects). This may be based on mathematical operations of numerical type table

For example: The number of all the number of boys than girls in the class number by 10 boys:

Class.objects.filter(boy_num__ge = F('girl_num')).update(boy_num = F('boy_num') - 10)

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""

The statement Django filter conditions are separated by commas and means, if desired, to perform more complex query, such as (or statements), you can use the query Q

For example: query a number of boys in the class greater than 20 or less than the number of girls 20

Class.objects.filter(Q(boy_num__gt = 20) | Q(girl_num_lt = 20))

Queries greater than the number of boys and 20 are girls in the class of not less than 20 people

Do not use query Q: Class.objects.filter (boy_num__gt = 20, girl_num__lt = 20)

Use Q Query: Class.objects.filter (Q (boy_num__gt = 20) & ~ Q (girl_num__lt = 20))

Mix: Class.objects.filter (Q (boy_num__gt = 20), girl_num__lt = 20)

Q query: | representative or operation, and operation & representatives, representatives of non-operation ~.

Q query parameters can be mixed with the target keyword parameters, all parameters (or keyword arguments provided to the query function Q  objects) are "AND" together. However, if there is Q  objects, it must precede all keyword arguments.

defer ( 'id', 'name '): fetch objects, fields except id and name are
only ( 'id', 'name '): take the object id and name only
if the point is still able to point out the other columns, but do not the point, because the column is not taken, it will query the database again

 

the User class (models.Model):
name = models.CharField (MAX_LENGTH = 32)
password = MyCharField (MAX_LENGTH = 32)
choices = ((. 1 'universities'), (2 'regular undergraduate'), (3, 'specialist'), (4, 'other'))
Education = models.IntegerField (choices = choices)

user_obj.education # get digital
user_obj.get_education_display () # usage fixed comment corresponding to the acquired choice field

get_field_display()

Guess you like

Origin www.cnblogs.com/wangqingjiang/p/11811994.html