1024programmer Java djangoQ query, ORM query optimization, transactions, common fields, three types of many-to-many, Ajax

djangoQ query, ORM query optimization, transactions, common fields, three types of many-to-many, Ajax

Table of contents

  • Today’s content details

    • Q query advanced operations
    • ORM Query Optimization
    • ORM Transaction Operations
    • ORM Common Field Types
    • ORM Common Fields Parameters
    • Ajax
    • Content-Type
    • ajax carries file data

Today’s content details

Q query advanced operation

from django.db.models import Q
q_obj = Q() # 1. Generate q object
q_obj.cOnnector= 'or' # The default connection of multiple conditions is and and can be modified as or
q_obj.children.append(('pk', 1)) # 2. Add query conditions
q_obj.children.append(('price__gt', 2000 )) # Support adding multiple
res = models.Book.objects.filter(q_obj) # Query supports directly filling in q objects
print(res)

ORM query optimization

1.ORM queries are lazy queries by default
2.ORM queries come with Pagination processing
3.only and defer
'''data object + data corresponding to the specified field'''
# res = models.Book.objects.only('title', 'price')
# print(res) # queryset [data object, data object]
# for obj in res:
# print(obj.title) # Click on the field filled in the brackets without entering the SQL query
# print(obj.price)
# print(obj.publish_time) # You can click on the fields not in the brackets to get the data but you can use SQL query

res = models.Book.objects.defer('title ', 'price')
# print(res) # queryset [data object, data object]
for obj in res:
# print(obj.title) # Click on the field filled in the brackets to run SQL Query
# print(obj.price)
print(obj.publish_time) # Click on the field that is not in the brackets to get the data without leaving the SQL query
4.select_related and prefetch_related
# res = models.Book .objects.all()
# for obj in res:
# print(obj.publish.name) # Each query requires SQL
# res = models.Book.objects.select_related(' authors') # Join tables first and then query encapsulation
# res1 = models.Author.objects.select_related('author_detail') # Many-to-many fields are not supported in brackets and the other two are OK
# print(res1)
# for obj in res:
# print(obj.publish.name) # No more SQL queries
res = models.Book.objects.prefetch_related('publish') # Subquery
for obj in res:
print(obj.publish.name)

ORM transaction operation

"""
1. Four major characteristics of transactions (ACID)
Atomicity, consistency, isolation, durability
2. Related SQL keywords
start transaction;
rollback;
commit;
savepoint;
3. Related important concepts
Dirty read, phantom read, non-repeatable read, MVCC multi-version control...
"""
Django ORM provides at least three ways to start transactions
Method 1: Add key-value pairs related to the configuration file database, globally valid
"ATOMIC_REQUESTS": True for each ORM involved in the request The operations belong to the same transaction
Method 2: Decorator is locally valid
from django.db import transaction
@transaction.atomic
def index():pass
Method 3: with context management is local Valid
from django.db import transaction
def reg():
with transaction.atomic():
pass

ORM common field types

AutoField
primary_key=True
CharField
max_length
IntegerField
BigIntergerField
DecimalField
max_digits decimal_places
DateField
auto_now auto_now_add
DateTimeField
auto_now auto_now_add
BooleanField
Pass a Boolean value and automatically store 0 or 1
TextField
Store large sections of text
EmailField
Store email format data
FileField
Automatically save the file object to a path configured in advance and store the path information

ORM also supports user-defined Define field type
class MyCharField(models.Field):
def __init__(self, max_length, *args, **kwargs):
self.max_length = max_length
super().__init__(max_length =max_length, *args, **kwargs)
def db_type(self, connection):
return 'char(%s)' % self.max_length
class User(models.Model):
name = models.CharField(max_length=32)
info = MyCharField(max_length=64)

ORM common field parameters

primary_key primary key
verbose_name comment
max_length field length
max_digits the total number of decimal digits
decimal_places the number of digits after the decimal point
auto_now automatically updates the data for each operation
auto_now_add creates an automatic update event for the first time and does not automatically update later
null allows the field to be empty
default field default value
unique unique value
db_index adds an index to the field
choices is used when the possibilities of a certain field can be fully enumerated
Gender, education, work status,...
class User(models.Model):
name = models.CharField(max_length=32)
info = MyCharField(max_length=64)
# List the corresponding relationships in advance
gender_choice = (
(1, 'Male'),
(2, 'Female'),
(3, 'Other'),
)
gender = models.IntegerField(choices=gender_choice,null =True)
user_obj = User.objects.filter(pk=1).first()
user_obj.gender
user_obj.get_gender_display()

to association table
to_field association Field (do not write the default associated data primary key)
on_delete When deleting data in the associated table, the behavior of the current table and its associated rows.
1. models.CASCADE
Cascade operation, when a connected piece of data in the main table is deleted, all the data associated with it in the slave table will be deleted at the same time
2. models.SET_NULL
When the main table When a row of data in the table is deleted, all related fields of the data associated with it in the table are set to null. At this time, please note that when defining a foreign key, this field must be allowed to be empty
3. models.PROTECT
When a row of data in the main table is deleted, since the relevant fields in the slave table are protected foreign keys, deletion is not allowed
4. models.SET_DEFAULT
When a row of data in the main table is deleted, the slave table The associated fields of all related data are set to default values. At this time, pay attention to when defining a foreign key. This foreign key field should have a default value
5. models.SET()
When a piece of data in the main table is deleted , all related data fields in the table are set to the values ​​set in SET(), similar to models.SET_DEFAULT, except that the relevant fields in the table do not need to set the default parameter
6. models.DO_NOTHING
Do nothing, everything depends on database-level constraints. Note that the default constraint at the database level is RESTRICT. This constraint is similar to models.PROTECT in django

Ajax

Asynchronous submission of partial refresh
ajax is not a new technology and there are many versions. We are currently learning the jQuery version (version It doesn’t matter, as long as the essence is the same)

Basic syntax
$.ajax({
url:'', // The three filling methods of the backend address are consistent with the action of the form tag
type: 'post', // The default request method is also get
data:{'v1':v1Val, 'v2':v2Val}, // Data sent
success:function (args) { // Backend return After the result, args is automatically triggered to receive the data returned by the backend
$('#d3').val(args)
}
})

Content-Type

1.urlencoded
The default encoding format of ajax and the default form are also
data format xxx=yyy&uuu=ooo&aaa=kkk
The django backend will automatically process it into request.POST

2.formdata
The django backend still processes ordinary key-value pairs into request.POST, but The file will be processed into request.FILES

3.application/json
The form does not support ajax.

The backend needs to obtain it from request.body and process it by itself.

ajax carries file data


This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/756365

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索