In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
Editor to share with you what django knowledge points, I believe that most people do not know much about it, so share this article for your reference, I hope you will learn a lot after reading this article, let's go to know it!
1. View function:
Request object-request:
1. HttpRequest.body: request the original data
2. HttpRequest.path: a string indicating the path component of the request (excluding domain name)
3 、 HttpRequest.method
4 、 HttpRequest.GET
5 、 HttpRequest.POST
6 、 HttpRequest.FILES
7. HttpResquest.user: an object of type AUTH_USER_MODEL
Response object:
Return HttpResponse ("") returns string instance
Return render (request, "template", {"": ""}) returns a string instance
Return rredirect ("/ index/") redirect
II. Template language
First, write the function in the views view function and return a rendered page:
Views:
Def foo (request):
Name= "li"
L = [111, 2222, 3333]
D = {"info": [obj1,obj2...]}
Return render (request, "index.html", locals ())
1. Variable: {{name}}
-query the period character in depth. For example: {{d.info.0.name}}
-filter {{name | date: "Y-m-d"}}
two。 Label:
For cycle
{% for i in 1%}
{{i}}
{% empty%}
There are no conditions to meet
{% endfor%}
If judgment statement
{if name= "li"%}
Yes
{% elif%}
{% endif....%}
3. Template syntax
(1) base.html: {% block con%} {% endblock%} in the master
(2) inherit the master index.html:
{% extends "base.html"%} inheritance
{% block con%}
{% endblock%}
3. Models model of ORM
1. Mapping relationship:
Class name of table name-Python in sql
Fields in sql-Class properties of Python
Records in sql-Class objects for Python
2. Single table operation
Class Article (models.Model):
Nid = models.BigAutoField (primary_key=True)
Title = models.CharField (max_length=50, verbose_name=' article title')
Read_count = models.IntegerField (default=0)
(1) add operation
Views:
Copy the code
# method 1:
The article_obj=models.Article.objects.create (nid=1,title= "yuan", read_count=12) # create method returns the currently created article object
# method 2:
Article_obj=models.Article (nid=1,title= "yuan", read_count=12)
Article_obj.save ()
Delete:
Models.Article.objects.filter (title= "python") .delete () # default cascading deletion
Modify:
Models.Article.objects.filter (title= "python") .update (read_count=F ("read_count") + 10)
Query API:
All (): query all results # QuerySet
Filter (* * kwargs): it contains the object # QuerySet that matches the given filter criteria
Get (* * kwargs): returns an object that matches the given filter criteria, and returns one and only one result
An error is thrown if there is more than one or none of the objects that meet the filter criteria. # model object
Exclude (* * kwargs): it contains objects # QuerySet that do not match the given filter criteria
Values (* field): returns a ValueQuerySet-- and a special QuerySet, and the result is not a series.
The instantiated object of model, but an iterative dictionary sequence # QuerySet
Values_list (* field): very similar to values (), it returns a tuple sequence, and values returns a dictionary sequence # QuerySet
Order_by (* field): sort query results # QuerySet
Reverse (): reverse sort the query results # QuerySet
Distinct (): removes duplicate records from the returned result # QuerySet
Count (): returns the number of objects in the database that match the query (QuerySet). # int
First (): returns the first record # model object
Last (): returns the last record # model object
Exists (): returns True if QuerySet contains data, otherwise returns False
QuerySet supports chained operations:
Models.Article.objects.all (). Filter (). Values (). Distinct (). Count ()
QuerySet data type:
1. Sliced and iterated [obj,....]
2. Lazy query:
Articles_list=models.Article.objects.all ()
Use articles_list, such as if articles_list, to convert the sql statement
3. Caching mechanism
Articles_list=models.Article.objects.all ()
For i in articles_list:
Print (i.title) # hit the database
For i in articles_list:
Print (i.title) # not hit the database
=
For i in models.Article.objects.all ():
Print (i.title) # hit the database
For i in models.Article.objects.all ():
Print (i.title) # hit the database
4. Optimize the query
Articles_list=models.Article.objects.all () .iterator ()
For i in articles_list:
Print (i.title) # hit the database
For i in articles_list:
Print (i.title) # No result
Concatenated table operation:
Table relationships:
Class UserInfo (AbstractUser): # settings: AUTH_USER_MODEL = "blog.UserInfo"
"
User information
"
Nid = models.BigAutoField (primary_key=True)
Nickname = models.CharField (verbose_name=' nickname', max_length=32,null=True)
Telephone = models.CharField (max_length=11, blank=True, null=True, unique=True, verbose_name=' mobile phone number')
Avatar = models.FileField (verbose_name=' avatar', upload_to='avatar', default= "avatar/default.png")
Create_time = models.DateTimeField (verbose_name=' creation time', auto_now_add=True)
Class Blog (models.Model):
"
Site information
"
Nid = models.BigAutoField (primary_key=True)
Title = models.CharField (verbose_name=' personal blog title', max_length=64)
Site = models.CharField (verbose_name=' personal blog suffix', max_length=32, unique=True)
Theme = models.CharField (verbose_name=' blog theme', max_length=32)
User = models.OneToOneField (to='UserInfo', to_field='nid')
Class Category (models.Model):
Nid = models.AutoField (primary_key=True)
Title = models.CharField (verbose_name=' classification title', max_length=32)
Blog = models.ForeignKey (blog to which verbose_name=' belongs', to='Blog', to_field='nid')
Class Article (models.Model):
Nid = models.BigAutoField (primary_key=True)
Title = models.CharField (max_length=50, verbose_name=' article title')
Desc = models.CharField (max_length=255, verbose_name=' article description')
# category field: the category object associated with the Article object
Category = models.ForeignKey (verbose_name=' article type', to='Category', to_field='nid', null=True)
# user field: the user field associated with the Article object
User = models.ForeignKey (user to which verbose_name=' belongs', to='UserInfo', to_field='nid')
Tags = models.ManyToManyField (
To= "Tag"
Through='Article2Tag'
Through_fields= ('article',' tag')
)
Class ArticleDetail (models.Model):
Nid = models.AutoField (primary_key=True)
Content = models.TextField (verbose_name=' article content',)
Article = models.OneToOneField (article of verbose_name='', to='Article', to_field='nid')
Class Article2Tag (models.Model):
Nid = models.AutoField (primary_key=True)
Article = models.ForeignKey (verbose_name=' article', to= "Article", to_field='nid')
Tag = models.ForeignKey (verbose_name=' tag', to= "Tag", to_field='nid')
Class Tag (models.Model):
Nid = models.AutoField (primary_key=True)
Title = models.CharField (verbose_name=' tag name', max_length=32)
Blog = models.ForeignKey (blog to which verbose_name=' belongs', to='Blog', to_field='nid'
Add record operation for associated table:
1. Create an article object:
User_obj=models.UserInfo.objects.get (nid=1)
Category_obj=models.Category.objects.get (nid=2)
# one-to-many relationship binding #
# method 1:
Article_obj=models.Article.objects.create (nid=5,title= "picking up every day", user=user_obj,category=category_obj)
# method 2:
Article_obj=models.Article.objects.create (nid=5,title= "picking up every day", user_id=1,category_id=2)
''
Article:
Nid title user_id category_id
5 Chaohua Xi pick up 1 2
''
# # many-to-many relationship binding #
If does not have a mediation model:
Tags = models.ManyToManyField ("Tag")
''
The third table created by ORM:
Article2tags:
Nid article_id tag_id
1 5 1
2 5 2
''
Example: bind kw1,kw2 tag to article_obj
Tag1=Tag.objects.filter (title=kw1) .first ()
Tag2=Tag.objects.filter (title=kw2) .first ()
Article_obj.tags.add (tag1,tag2) #
Article_obj.tags.add (* [tag1,tag2])
Article_obj.tags.add (1 dint 2)
Article_obj.tags.add (* [1pc2])
Dissolve the relationship:
Article_obj.tags.remove (tag1,tag2)
Article_obj.tags.clear ()
Reset the relationship:
Article_obj.tags.clear ()
Article_obj.tags.add (tag1,tag2)
=
Article_obj.tags.set (tag1,tag2)
If has an intermediary model:
Tags = models.ManyToManyField (
To= "Tag"
Through='Article2Tag'
Through_fields= ('article',' tag')
)
Class Article2Tag (models.Model): # Mediation Model
Nid = models.AutoField (primary_key=True)
Article = models.ForeignKey (verbose_name=' article', to= "Article", to_field='nid')
Tag = models.ForeignKey (verbose_name=' tag', to= "Tag", to_field='nid')
Bind a many-to-many relationship, have an intermediary model, and can no longer use article_obj.tags.add (), remove () and other methods
You can only use the Article2Tag table for instance objects.
Example: bind kw1,kw2 tag to article_obj:
Models.Article2Tag.objects.create (tag_id=1,article_id=5)
Models.Article2Tag.objects.create (tag_id=2,article_id=5)
Copy the code
Join table operation (object-based query):
Copy the code
One-to-many queries:
Example 1: query the classified name of the article whose primary key is 4 (forward query, by field)
Article_obj=models.Article.objects.get (nid=4)
Print (article_obj.category.title)
SELECT * FROM "blog_article" WHERE "blog_article". "nid" = 4; / / category_id=2
SELECT * FROM "blog_category" WHERE "blog_category". "nid" = 2
Example 2: query all articles published by user yuan (reverse query, table name _ set)
Yuan=models.UserInfo.objects.get (username= "yuan")
Book_list=yuan.article_set.all () # QuerySet
Many-to-many queries:
Example 3: query the tag name of an article with a primary key of 4 (forward query, by field)
Article_obj=models.Article.objects.get (nid=4)
Tag_list=article_obj.tags.all () # finds the associated tag record in the tag table through Article2Tag
For i in tag_list:
Print (i.title)
Example 4: query all articles corresponding to this tag developed by web (reverse query, by table name _ set)
Tag_obj=models.Tag.objects.get (title= "web Development")
Article_list=tag_obj.article_set.all ()
For i in article_list:
Print (i.title)
Example 5: query the author names of all articles corresponding to this tag developed by web
Tag_obj=models.Tag.objects.get (title= "web Development")
Article_list=tag_obj.article_set.all ()
For article in article_list:
Print (article.user.username)
Cross-table query based on QuerySet (forward query, by field; reverse query, by table name)
One-to-many queries:
Example 1: query the classification name of an article with a primary key of 4
Models.Article.objects.filter (nid=4) .values ("category__title")
Models.Category.objects.filter (article__nid=4) .values ("title")
Example 2: query all articles published by user yuan
Models.UserInfo.objects.filter (username= "yuan") .values (article__title)
Models.Article.objects.filter (user__username= "yuan") .values ("title")
Many-to-many queries:
Example 3: query the tag name of an article with a primary key of 4 (forward query, by field)
Models.Article.objects.filter (nid=4) .values ("tags__title")
Models.Tag.objects.filter (article__nid=4) .values ("title")
Example 4: query all articles corresponding to this tag developed by web (reverse query, by table name _ set)
Models.Article.objects.filter (tags__title= "web development"). Values ("title")
Models.Tag.objects.filter (title= "web development"). Values ("article__title")
Example 5: query the author names of all articles corresponding to this tag developed by web
Models.Tag.objects.filter (title= "web development"). Values ("article__user__username")
Models.UserInfo.objects.filter (article__tags__title= "web development"). Values ("username")
The above is all the contents of the article "what are the knowledge points of django". 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.