Django a foundation

ORM relationship building

Is not considered a foreign key, first create a base table

One generally used in case of need to outline (a table would have been possible, split became two tables, it becomes one)

Many foreign key field is set in the "many" table goes

Many to many need to establish a separate table to set up foreign key relationships

Library management systems

On the table

from django.db import models
# 先创建基表,暂不考虑外键
class Book(models.Model):
    title = models.CharField(max_length=32)
    price = models.DecimalField(max_digits=8, decimal_places=2)
    publish = models.Foreignkey(to='Publish')
    # to用来指代跟哪张表有关系 默认关联的就是表的主键字段
    

Press table:

class publish(models.Model):
    title = models.Charfield(max_length=32)
    age = models.EmailField()

On the table:

class Author(models.Model):
    name = models.CharField(max_length=32)
    age = models.IntegerField()
    

Time-to-many foreign key field created to synchronize data table fields will automatically add the suffix _ id

If you add up _ id, orm will then later add a _ id
so you write many foreign key field do not try to be smart when adding _id

To-many relationship between the foreign key fields built in but any party may recommend that you build in one of the higher frequency queries

One to one relationship table foreign key field built in either one can but recommend that you build in one of the higher frequency queries

author = models.ManyToManyField(to='Author')  
# django orm会自动帮你创建书籍 和作者的第三张关系表
# author这个字段是一个虚拟字段 不能在表中展示出来 仅仅只是起到一个告诉orm 建第三章表的关系的作用

Lifecycle flowchart request django

urls.py routing layer

Routing match

url The first parameter is a regular expression as long as the regular expression can be matched to the content
will be executed immediately view function back down rather than continue the match

# 取消django自动让浏览器加斜杠的功能
    APPEND_SLASH = False  # 该参数默认是True
from app01 import views

urlpatterns = [
    url(r'^admin/', admin.site.urls),  # url第一个参数是一个正则表达式
    url(r'^test/$', views.test),  # 一旦正则表达式能够匹配到内容 会立刻结束匹配关系 直接执行后面对应的函数
    url(r'^testadd/$', views.testadd),
]
# django匹配路由的规律
# 不加斜杠 先匹配一次试试 如果匹配不上 会让浏览器重定向 加一个斜杠再来一次 如果还匹配不上 才会报错
"""
路由匹配值匹配url部分
不匹配?后面的get携带的参数
"""

Unknown group:

The regular expression matching the packet contents to a position as the function parameters are passed to the view

url(r'^test/([0-9]{4})/', views.test)
test() takes 1 positional argument but 2 were given

When you have packet routing regex position parameters so as to match the content in view of the function performed when the next regular expression matching to the contents of a packet will be passed to the view function

test (request, the regular expression matching the packet content)

Well-known groups:

Regular expression match to the contents of the packet will be used as a key parameter passed to the view function

url(r'^testadd/(?P<year>\d+)/', views.testadd),
testadd() got an unexpected keyword argument 'year'

When your route and there is packet to the packet surnamed So when matching content will be grouped within the regular expression matching to the content as keyword arguments passed to the view function

testadd (request, year = positive expression within the packet matches the content)

The use of famous and anonymous group we can pass additional parameters to a function before calling function view

Note: grouping known and unknown groups can not be mixed

A packet but the same case may be used multiple times
unknown can have multiple: url (r '^ index / (\ d +) / (\ d +) /', views.index),
known there may be multiple: url (r '^ index / (? P \d+)/(?P \ d +) / ', views.index ),
but it is not mixed

Reverse lookup

According to an alias dynamically parses a url results can directly access the corresponding result, the process is the reverse analysis

The first case: the route is not a regular expression is written directly to death

url(r'^home/', views.home,name='xxx'),  # 给路由与视图函数对应关系起别名
        
前端反向解析
    {% url 'xxx' %}
        
后端反向解析
    from django.shortcuts import render,HttpResponse,redirect,reverse
    url = reverse('xxx')

The second case: what reverse lookup unknown packets while parsing you need to manually specify the contents of a regular match

url(r'^home/(\d+)/', views.home,name='xxx'),  # 给路由与视图函数对应关系起别名
前端反向解析
<p><a href="{% url 'xxx' 12 %}">111</a></p>
<p><a href="{% url 'xxx' 1324 %}">111</a></p>
<p><a href="{% url 'xxx' 14324 %}">111</a></p>
<p><a href="{% url 'xxx' 1234 %}">111</a></p>
        
后端反向解析
url = reverse('xxx',args=(1,))
url1 = reverse('xxx',args=(3213,))
url2 = reverse('xxx',args=(2132131,))
# 手动传入的参数 只需要满足能够被正则表达式匹配到即可

The third case:

Reverse lookup famous packets when parsing the content you need to manually specify the regular match what
reverse analysis can be grouped, like the famous anonymous group
but the most formal of this wording should be as follows:

url(r'^home/(?P<year>\d+)/', views.home,name='xxx'),  
# 给路由与视图函数对应关系起别名
        
前端
# 可以直接用无名分组的情况
<p><a href="{% url 'xxx' 12 %}">111</a></p>
# 你也可以规范写法
<p><a href="{% url 'xxx' year=1232 %}">111</a></p>  # 了解即可
后端
# 可以直接用无名分组的情况
url = reverse('xxx',args=(1,))
# 你也可以规范写法
url = reverse('xxx',kwargs={'year':213123})  # 了解即可
        
以编辑功能为例
url(r'^edit_user/(\d+)/',views.edit_user,name='edit')
            
def edit_user(request,edit_id):
# edit_id就是用户想要编辑数据主键值
pass
            
{% for user_obj in user_list %}
<a href='/edit_user/{{user_obj.id}}/'>编辑</a>
<a href='{% url 'edit' user_obj.id %}'>编辑</a>
{% endfor %}

Route distribution (******)

Premise
in all the django app can have its own independent urls.py templates static
Because of the above features you use django development projects will be able to completely do not interfere with each other to develop multiplayer grouping
everyone to develop their own app only
group leader app owners only need to integrate the development of a project django empty inside
and register settings in the configuration file and then use the route distribution will be more integrated into the app to complete the stitching together of large projects

The total route is the route distribution project to solve the case of matching too many relationships

Using the route distribution, making the total routes do not match live and just do the task distribution (not correspondence between the total route after the request came
to ask you which app only functions to be accessed and then forwards the request to the corresponding app to handle)

from app01 import urls as app01_urls
from app02 import urls as app02_urls

urlpatterns = [
    url(r'^admin/', admin.site.urls),  # url第一个参数是一个正则表达式
    # 路由分发
    url(r'^app01/',include(app01_urls)),  # 路由分发需要注意的实现 就是总路由里面不能以$结尾
    url(r'^app02/',include(app02_urls)),
    ]
# 子路由
from django.conf.urls import url
from app01 import views

urlpatterns = [
       url('^reg/',views.reg)
    ]
from django.conf.urls import url
from app02 import views

urlpatterns = [
    url('^reg/',views.reg)
    ]

最省事的写法(******)
url(r'^app01/',include('app01.urls')),
url(r'^app02/',include('app02.urls'))

Namespaces

When multiple app appears in case of conflict since the alias you are doing when routing distributed to each app can create a namespace
you can then choose when to reverse resolved in the end which namespace lookup alias

url(r'^app01/',include('app01.urls',namespace='app01')),
url(r'^app02/',include('app02.urls',namespace='app02'))
        
# 后端
print(reverse('app01:reg'))
print(reverse('app02:reg'))
# 前端
<a href="{% url 'app01:reg' %}"></a>
<a href="{% url 'app02:reg' %}"></a>

In fact, when the above namespace knowledge can not completely guarantee that the alias you just need the time throughout the conflict can not be django project. Surnamed unified application name plus the prefix

urlpatterns = [
            url(r'^reg/',views.reg,name='app02_reg')
                ]
                
urlpatterns = [
            url('^reg/',views.reg,name='app01_reg')
                ]

Pseudo-static

A dynamic Web page disguised as a static web page in order to very good SEO search engine query frequency and intensity wishlists

The so-called search engines do not actually a huge reptiles

Optimized arrived, but no matter how good or RMB players

Virtual Environment

Module to module does not require every item of equipment needed for the project and will not install

Each will create a virtual environment similar to you to re-download a pure python interpreter
after the project above what you used to install (N can have multiple virtual environments on a single machine)
do not create unlimited virtual machines on your surroundings

django version difference
django1.X django2.X

urls.py中路由匹配的方法有区别
django2.X用的是path
    urlpatterns = [
        path('admin/', admin.site.urls),
    ]
django1.X用的是url
    urlpatterns = [
        url(r'^reg.html',views.reg,name='app02_reg')
    ]
# 区别 django2.X里面path第一个参数不是正则也不支持正则 写什么就匹配什么
# 虽然path不支持正则 感觉也好用 django2.X还有一个re_path的方法 该方法就是你django1.X里面url
虽然path不支持 但是它提供了五种转换器  能够将匹配到的数据自动转黄成对应的类型
除了有默认五种转换器之外 还支持你自定义转换器

View layer

How to upload files form the form the backend Get File
matters form expression transfer files Note
1.method must be changed to post
2.enctype the format to formdata
early post toward the rear end you use when you need to send the requested settings configuration file comments out of a middleware csrf

Guess you like

Origin www.cnblogs.com/allenchen168/p/11939292.html