Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Case Analysis of Django Model layer

2025-01-21 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains the "Django model layer case analysis", the content of the article is simple and clear, easy to learn and understand, now please follow the editor's ideas slowly in depth, together to study and learn "Django model layer case analysis"!

1. F query

In all the above examples, the filter we constructed simply compares the field value with a constant that we set ourselves. What if we want to compare the values of the two fields?

Django provides F () to make such a comparison. An instance of F () can reference a field in a query to compare the values of two different fields in the same model instance.

Example:

Build a table:

Fromdjango.dbimportmodels

ClassGoods (models.Model):

Name=models.CharField (max_length=32)

Price=models.DecimalField (max_digits=8,decimal_places=2)

Remain=models.BigIntegerField ()

Sold_out=models.BigIntegerField ()

Insert module

Fromdjango.db.modelsimportF,Q

Example: query the names of goods sold more than the number of goods in stock

Res=models.Goods.objects.filter (sold_out__gt=F ('remain')). Values_list (' name','sold_out','remain')

Print (res)

#

F can help us get the corresponding value of a field in the table as my filter condition, rather than what I think is a custom constant, realizing the effect of dynamic comparison.

Django supports addition, subtraction, multiplication, division and modular operations between F () objects and between F () objects and constants. Based on this, the numerical types in the table can be mathematically operated.

Example: increase the price of each commodity by 50 yuan

Res1=models.Goods.objects.update (price=F ('price') + 100)

Extension: how to modify the char field, such as adding the word "clearance" at the end of all the commodity names in the above table, how to do it?

Here you need to use two modules: Concat and Value

Fromdjango.db.models.functionsimportConcat

Fromdjango.db.modelsimportValue

Res=models.Goods.objects.update (name=Concat (F ('name'), Value (' clearance'))

Concat means to perform string stitching operation. The parameter position determines whether the splicing is in the head or tail. The stitching value to be added in Value is the stitching value to be added.

2. Q query

The condition of the comma get summarized by the filter () method is the relationship with. If you want to execute a more complex query, such as the or statement, you will use the Q object.

Example:

Query the names of goods whose quantity is more than 100 or the price is less than 300

Fromdjango.db.modelsimportF,Q

Res=models.Goods.objects.filter (Q (sold_out__gt=100) | Q (price__lt=300)) .values_list ('name','sold_out','price')

Print (res)

When the condition is wrapped with Q, filter can support the cross-union comparator.

# query products whose inventory number is less than or equal to 20 and the number sold is not 10

Res=models.Goods.objects.filter (Q (remain__lte=20) & Q (sold_out=12)). Values_list ('name')

We can combine the & and | operators and group them in parentheses to write arbitrarily complex Q objects.

At the same time, Q objects can be inverted using the ~ operator, which allows you to combine normal queries with NOT queries.

# query products whose names contain new or popular styles and whose inventory is greater than 60

Res=models.Goods.objects.filter (Q (name__contains=' New') | Q (name__contains=' Fashion'), remain__gt=60) .values_list ('name')

Query functions can mix Q objects and keyword parameters. All parameters supplied to the query function (keyword arguments or Q objects) will be "AND" together. However, if the Q object appears, it must precede all keyword parameters

Focus on the use of methods to supplement:

Instantiate Q object: QroomQ ()

Q.connector='or'# defaults that the condition between Q is the and relation, which is changed to the or relation.

Q.children.append (('name','sgt')) # insert the first condition. Note that a meta-ancestor is passed here.

Q.children.append (('password','123')) # you can continue to insert conditions

# Q objects are supported to be placed directly in filter parentheses. The default is and relationship, which can be modified into or relationship by q.connectseparator 'above.

Models.User.objects.filter (Q) # these are the conditions of the query. By default, they are and relations, which can be changed to or relations.

III. Affairs

Definition: turn multiple sql statement operations into atomic operations, or succeed at the same time, and one failure will be rolled back to the original state to ensure data integrity and consistency (NoSQL database partially supports transactions)

# transaction

# Buy goods

# modified data in the product table: number sold + 1, inventory-1

Fromdjango.db.modelsimportF

Fromdjango.dbimporttransaction

Try:

Withtransaction.atomic ():

Models.Goods.objects.filter (id=1) .update (remain=F ('remain')-1 ~ (sold_out')) + 1)

ExceptExceptionase:

Print (e)

Fourth, some common operations to supplement

The difference between update () and save ()

Both are operations to modify and save the data, but the save () function rewrites all the data items in the data column, while update () updates the modified items with high efficiency and less time.

So later changes to the data are saved with update ()

When we operate on the database through orm, let the terminal display the internal query operation sql statement:

In the settings.py file of the Django project, copy and paste the following code at the end:

LOGGING= {

'version':1

'disable_existing_loggers':False

'handlers': {

'console': {

'level':'DEBUG'

'class':'logging.StreamHandler'

}

}

'loggers': {

'django.db.backends': {

'handlers': ['console']

'propagate':True

'level':'DEBUG'

}

}

}

After configuration, when any statements that operate on the database are executed, the sql statements executed by Django will be automatically printed to the pycharm terminal.

Add:

In addition to configuration, you can also view the query statement through a bit of query, as shown below:

Only and defer

What you get is an object, and the two are opposite.

(prerequisite setting: set that every time you operate the database, there will be a sql statement on the pycharm terminal. The steps are described above)

Let's take a look at only:

Look at defer.

Choice attribute

The choice attribute is used to limit the range of choices the user can make. Such as the choice of gender (male or female)

ClassMyUser (models.Model):

Name=models.CharField (max_length=32)

Password=models.CharField (max_length=32)

Choices= ((1) 'male'), ((2) 'female'), ((3))

Gender=models.CharField (choices=choices,default=1,max_length=5)

Choice receives a tuple (guaranteed values are immutable), just as each option consists of a tuple (value,display_name). Obviously, display_name is meant to be displayed on the page.

How to get value and displayname?

For example, an instance of a User object user_obj

User_obj.gender=value (value by attribute)

User_obj.get_gender_display () = display_name (get display_name through the get_ attribute _ display () method)

You can simply display value in the template through the template language {{user_obj.gender}}, but you cannot directly call the get attribute _ display method (the template is a template language after all). To solve this problem, you can use a custom filter:

Review how to customize the filter:

1. Create a new folder called templatetags under the application name

2. Create a new py file in this folder with an arbitrary name

3, add fixed code and custom filter code to the py file

Fromdjangoimporttemplate

Register=template.Library ()

@ register.filter (name='displayName')

DefdisplayName (obj):

Res=obj.get_gender_display

Returnres ()

# View layer:

Fromdjango.shortcutsimportrender,HttpResponse,reverse

# Createyourviewshere.

Fromapp01importmodels

Defindex (request):

Obj=models.MyUser.objects.filter (pk=1) .first ()

Returnrender (request,'index.html',locals ())

# frontend (html page):

{% loadmy_file%}

{{obj | displayName}}

Bulk_create inserts data in bulk

When we use orm to add a lot of table records at one time, the waiting time for results will be very slow. If we need to insert a lot of data in batches at one time, we need to use bulk_create to insert data in bulk.

Importrandom

User_list= ['user [{}]' .format (I) foriinrange (100)]

Data= []

Forjinuser_list:

Data.append (models.MyUser (name=j,password='123',gender=str (random.choice ([1pm 2pm 3])

Models.MyUser.objects.bulk_create (data)

Select_related and prefetch_related

Defselect_related (self,*fields)

Performance related: join joins tables between tables to obtain the associated data at one time.

Summary:

1.select_related mainly optimizes one-to-one and many-to-one relationships.

2.select_related uses SQL's JOIN statement for optimization to optimize and improve performance by reducing the number of SQL queries.

Defprefetch_related (self,*lookups)

Performance related: multi-table join table operation will be slow, use it to execute multiple SQL queries to achieve join table operation in Python code.

Thank you for reading, the above is the content of "Django model layer case analysis". After the study of this article, I believe you have a deeper understanding of the problem of Django model layer case analysis, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report