In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >
Share
Shulou(Shulou.com)05/31 Report--
Editor to share with you how to solve the case-insensitive problem of query results in django orm, I believe most people do not know much about it, so share this article for your reference. I hope you will gain a lot after reading this article. Let's learn about it together.
1.1.1 generate query
After you create the data model, django will automatically provide you with the database abstract API, which can create, obtain, modify, and delete objects. This document explains how to use API.
Let's refer to the following model, a weblog:
# class Blog (models.Model): name = models.CharField (max_length=100) tagline = models.TextField () def _ unicode__ (self): return self.name# author class Author (models.Model): name = models.CharField (max_length=50) email = models.EmailField () def _ unicode__ (self): return self.name# directory class Entry (models.Model): blog = models .ForeignKey (Blog) headline = models.CharField (max_length=255) body_text = models.TextField () pub_date = models.DateTimeField () authors = models.ManyToManyField (Author) n_comments = models.IntegerField () n_pingbacks = models.IntegerField () rating = models.IntegerField () def _ unicode__ (self): return self.headline
1.1.2 create an object
Using python objects to describe the data of database tables, django uses an intuitive system, a model class describes a data table, an instance of a class describes a detailed record of the table. Use the model's save () method to create the object to the database.
From mysite.blog.models import Blogb = Blog (name='Beatles Blog', tagline='All the latest Beatles news.') b.save ()
It is only when the save method is executed that django executes sql to write objects to the database.
1.1.3 Save modified objects
Still use the save () method to save changes
B5.name = 'New name'b5.save ()
1.1.4 Save the ForeignKey and ManyToManyField fields
Cheese_blog = Blog.objects.get (name=== Author.objects.create (name=)
1.1.5 retrieve objects
To retrieve objects from the database, you can build QuerySet through the Manage of the model. A QuerySet represents a combination of objects in a database. It can have 0 one or more filter conditions. In SQL, QuerySet is equivalent to select statements filtered by where or limit. You get the QuerySet through the Manage of the model, and each model has at least one Manage
1.1.6 retrieve all objects
The easiest way to retrieve all the data in the table is to use all ().
All_entries = Entry.objects.all ()
1.1.7 filtering to retrieve specific objects
There are two ways to retrieve and filter specific query results.
Filter (* * kwargs) returns a new QuerySet after matching query parameters
Exclude (* * kwargs) returns a new QuerySet after mismatching query parameters
Entry.objects.filter (pub_date__year=2006)
1.1.8 Link filtering
Entry.objects.filter (headline__startswith='What') .filter (pub_date__gte=datetime.now ()) .filter (pub_date__gte=datetime (2005, 1, 1))
1.1.9 filtering result set is unique
Every time you finish a QuerySet, you get a whole new result set, not including the previous one. Each completed result set can be stored, used or reused Q1 = Entry.objects.filter (headline__startswith= "What") Q2 = q1.exclude (pub_date__gte=datetime.now ()) Q3 = q1.filter (pub_date__gte=datetime.now ())
The three QuerySets are separate, the first is the result set where headline begins with the word "What", the second is a subset of the first, that is, the pub_date is no larger than the present, the third is a subset of the first, and the pub_date is greater than the present.
1.2.1 result set is delayed
QuerySets is delayed, the creation of QuerySets does not touch database operations, you can merge multiple filters together, until the evaluation time django will start the query. Such as:
Q = Entry.objects.filter (headline__startswith= "What") Q = q.filter (pub_date__lte=datetime.now ()) Q = q.exclude (body_text__icontains= "food") print Q
Although it appears that three filter conditions are executed, it is only when print Q is finally executed that django starts to query and execute SQL to the database.
1.2.2 other QuerySet methods
In most cases you use all (), filter (), and exclude ()
1.2.3 restrict QuerySets
Use python's array restriction syntax to qualify QuerySet, such as:
Take the first five
Entry.objects.all () [: 5]
Take the fifth to the tenth
Entry.objects.all () [5:10]
In general, restrict QuerySet to return a new QuerySet and will not evaluate the query immediately unless you use the "step" parameter
Entry.objects.all () [: 10:2] Entry.objects.order_by ('headline') [0] Entry.objects.order_by (' headline') [0:1] .get ()
1.2.4 Field Lookup
Field lookups are WHERE conditional clauses that specify SQL statements, and query keywords are specified through the QuerySet methods filter (), exclude (), and get ().
Basic query field__lookuptype=value
For example:
Entry.objects.filter (pub_date__lte='2006-01-01')
Convert to SQL:
SELECT * FROM blog_entry WHERE pub_date 14Blog.objects.filter (pk__gt=14)
Cross query
Entry.objects.filter (blog__id__exact=3) # Explicit formEntry.objects.filter (blog__id=3) # _ _ exact is impliedEntry.objects.filter (blog__pk=3) # _ _ compete for implies _ _ id__exact
Like statement escapes percent sign
Entry.objects.filter (headline__contains='%')
Escape to
SELECT... WHERE headline LIKE'%\%'
1.2.7 caching query set
Each QuerySet contains a cache to minimize access to the database. It is important to understand how he works and to write the most efficient code.
In the newly created QuerySet, the cache is empty. The first time the QuerySet is taken, so the database query occurs, the django caches the query results and returns them to the request, and the subsequent query values reuse the results in the cache.
Keep the habit of caching, because it will be troublesome if you don't use query caching correctly. For example, the following example creates two QuerySet
Print [e.headline for e in Entry.objects.all ()] print [e.pub_date for e in Entry.objects.all ()]
This means that the database query is executed twice and the database is actually loaded twice
To avoid this problem, simply save QuerySet reuse
Queryset = Poll.objects.all () print [p.headline for p in queryset] # Evaluate the query set.print [p.pub_date for p in queryset] # Re-use the cache from the evaluation.
1.2.8 compare object
Compare two model instances, using the python standard operator, with two equal signs = =
Some_entry = other_entrysome_entry.id = = other_entry.idsome_obj = = other_objsome_obj.name = = other_obj.name
1.2.9 deleting objects
Delete method is very convenient. The method is called delete (). This method directly deletes the object and does not return a value.
E.delete ()
You can also delete objects in batches. Each QuerySet has a delete () method, which can delete all objects in the QuerySet.
1.3.1 modify multiple objects at a time
Sometimes if you want to assign a specific value to a field of all objects in QuerySet, you can use the update () method
For example:
# Update all the headlines with pub_date in 2007.Entry.objects.filter (pub_date__year=2007) .update (headline='Everything is the same')
This method can only be used for unrelated fields and foreign keys
B = Blog.objects.get (pk=1) # Change every Entry so that it belongs to this Blog.Entry.objects.all () .update (blog=b)
The update () method does not return any value, and QuerySet does not support the save method. If you want to execute save, you can do the following:
For item in my_queryset:item.save ()
Update can also use F ()
# THIS WILL RAISE A FieldErrorEntry.objects.update (headline=F ('blog__name'))
1.3.2 Relational object
When you define a relationship in model, the model instance has a convenient API to access the relationship object. Using the model above on this page, for example, an Entry
Object can get the blog object and access the blog property e.blog.
Django also creates an API to access the other side of the relational object, and a blog object accesses the Entry list b.entry_set.all ().
1.3.3 One-to-many relationship
If an object has ForeignKey, the model instance accesses the relational object through simple properties
E = Entry.objects.get (id=2) e.blog # Returns the related Blog object.
You can obtain and assign values with foreign key attributes, and modify foreign key values until you execute the save () method to save them to the database.
E = Entry.objects.get (id=2) e.blog = some_bloge.save ()
If ForeignKey sets null=True, you can assign it to None.
E = Entry.objects.get (id=2) print e.blog # Hits the database to retrieve the associated Blog.print e.blog # will not fetch from the database; use the value in the cache. E = Entry.objects.select_related () .get (id=2) print e.blog # will not fetch from the database; use the value in the cache. Print e.blog # will not fetch from the database Use the value in the cache. B = Blog.objects.get (id=1) b.entry_set.all () # return all blog associated objects. # b.entry_set is a Manager that returns QuerySets.b.entry_set.filter (headline__contains='Lennon') b.entry_set.count () b = Blog.objects.get (id=1) b.entries.all () # return all blog associated objects # b.entries is a Manager that returns QuerySets .b.entries.filter (headline__contains='Lennon') b.entries.count ()
Add (obj1, obj2,...) Add multiple relational objects
Create (* * kwargs) to create new objects
Remove (obj1, obj2,...) Remove multiple relational objects
Clear () cleans up all relational objects
B = Blog.objects.get (id=1) b.entry_set = [E1, e2]
1.3.4 Many-to-many relationship
E = Entry.objects.get (id=3) e.authors.all () # returns all Entry authors .e.authors.count () e.authors.filter (name__contains='John') a = Author.objects.get (id=5) a.entry_set.all () # returns all entry of Author.
1.3.5 One-to-one relationship
Class EntryDetail (models.Model): entry = models.OneToOneField (Entry) details = models.TextField () ed = EntryDetail.objects.get (id=2) ed.entry # returns the Entry object. These are all the contents of this article entitled "how to solve the case-insensitive problem of query results in django orm". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.