Part III: Django routing system

Create table relationships

The relationship between the table and the table: one to one, one to many, many to many

How to determine the relationship between the table and the table?

Transposition of perspective to consider the

To library management system as an example:

Book Table

  • Books and publishers is a foreign key to many relationship
  • Many of the foreign key relationship, the foreign key field is established in one of the multiple frequency

Press table

On the table

  • Book and author is a foreign key many relationship
  • Many to many foreign key relationship, the foreign key field, whether built in which tables are inside
  • But it is recommended to establish a relatively high frequency in the query goes on the table

Author Details Table

  • On the table is one of the details of the foreign key relationships
  • One foreign key relationship between the foreign key field built in which tables are inside
  • But the recommendation based on that table to use higher frequencies

Foreign key party to establish a higher frequency of use, convenience behind us orm-based query

Django establish table relationships

It will field a name and another table's primary key field automatically associate and establish a foreign key relationship

Many:字段名 = models.Foreignkey(to='表名')

Many to many:字段名 = models.ManyToManyField(to='表名')

One:字段名 = models.OneToOneField(to='表名')

ForeignKeyField and OneToOneFieldfield, when creating a table to the field orm automatically add _idthe suffix, regardless of whether they carry themselves. Therefore field named:字段名_id

# 在书写表关系的时候 要先把基表全部写出来 之后再考虑外键字段
from django.db import models

# Create your models here.
class Book(models.Model):
    # id是自动创建的 我们就不写了
    title = models.CharField(max_length=64)
    # price为小数字段 总共8位小数位占2位
    price = models.DecimalField(max_digits=8,decimal_places=2)

    # 书籍与出版社 是一对多外键关系
    publish = models.ForeignKey(to='Publish')  # 默认关联字段就是出版社表的主键字段
    # publish = models.ForeignKey(to=Publish)  # to后面也可以直接写表的变量名 但是需要保证该变量名在当前位置的上方出现

    # 书籍与作者   是多对多外键关系
    authors = models.ManyToManyField(to='Author')  # 书籍和作者是多对多关系
    """
    authors字段是一个虚拟字段 不会真正的在表中创建出来
    只是用来告诉django orm 需要创建书籍和作者的第三张关系表
    """

class Publish(models.Model):
    name = models.CharField(max_length=64)
    addr = models.CharField(max_length=64)


class Author(models.Model):
    name = models.CharField(max_length=32)
    phone = models.BigIntegerField()
    # 一对一外键关系建立
    author_detail = models.OneToOneField(to='AuthorDetail')


class AuthorDetail(models.Model):
    age = models.IntegerField()
    addr = models.CharField(max_length=255)

DjangoLifecycle flowchart request

DjangoThe routing system

URL configuration ( urls.py) similar sites directory, it is the nature of the mapping table between the URL and view functions.

In this way tell django, this URL call this code, the URL call that code.

URL conf Configuration

The basic format

from django.conf.urls import url
from app名字 import 视图名字

urlpatterns = [
     url(正则表达式, views视图函数,参数,别名),
]


urlpatterns = [
    url(r'^/$', views.home)  # 为网站首页的标准写法,默认匹配后缀为空url路径调用views.home函数
    url(r'^admin/', admin.site.urls),
    url(r'^index/$', views.index),
    url(r'^login/$', views.login),
]
  • Regular expression: a regular expression string, according to the routes that match the regular matching, it can be matched to the regular once content, performs a function corresponding view immediately matched not continue.

  • views view function: a callable object, typically a string path view function is designated as a view or function
  • Parameters: The optional parameters to be passed to the default view function (a dictionary)
  • Alias: An optional parameter name

Regular Expressions

^Match begins with a character, if you do not write here will cause the front of the letter just lose, as long as the end is the test / would match, such as: sdfsdfasdfasdtest/can also be recognized.

If write-only /, such as: (test /), in fact, there have been two requests: When a user enters an address in the url https://www.xxx.com/testafter the scan and found no test, after the browser will automatically add one more at the end of the test /, this time scans to test .

So the first request is not found, django will be 301 redirect, so the browser behind url plus a / try again.

# 如果不写^表达式,只写/
urlpatterns = [
    url(r'test/', views.test),
    url(r'testadd/', views.testadd),
]

Users input url, django will automatically help us add /, the following parameters can be settings.pyin 添加并修改(默认没有)is False, it will automatically add the ban/

APPEND_SLASH = True  # 自动加斜杠

Unknown group

When routing to match a certain regular expression parentheses

When the brackets will match the regular expression matching to the contents of the parameters passed to the corresponding position as the view function

# 无名分组
url(r'^test/([0-9]{4})/',views.test)  # 会将括号内的内容当做位置参数传入视图函数中的args
# 视图函数
def index(request,args):
    return HttpResponse('')

Famous grouping

To some regular expression from an alias

When matching the regular expression parentheses will be matched to the content as the key corresponding to the parameters passed to the view function

# 有名分组
url(r'^test/(?P<year>\d+)/', views.test)

# 视图函数
def index(request, year)  # 此处的year必须和有名分组中的year保持一致,因为是关键字参数,并不是位置参数,不可以像位置参数那样用形参接收。

Unknown packets and known packets can not be mixed, although it is not mixed, but the same naming scheme, a plurality of, as long as the corresponding number of the received parameters, or parameters corresponding key function to view.

Reverse lookup

The routing function corresponds to the view from a relation name, front and rear ends by some methods, a result can be obtained according to the name, the access result corresponding to url

This entire project name can not be repeated

Instructions:

Give the routing function and view correspondence between a name:

url(r'^testadd/', views.testadd, name='add')  # name后面跟的就是名字

Front-end analysis:

{% url 'add' %}

Back-end analysis:

# 需要导入reverse模块
from django.shortcuts import render, HttpResponse, redirect, reverse

reverse('add')

Unknown Packet reverse lookup

# 无名分组反向解析
url(r'^testadd/(\d+)/', views.testadd, name='add')

# 前端解析
{% url 'add' 1 %}

# 后端解析
reverse('add', args=(12,))

Famous grouping reverse lookup

# 前端解析
{% url 'edit_user' user_obj.id %}  # 推荐使用
# 执行name为'edit_user'的url中的视图函数,并将user_obj.id一并传入url中的函数
{% url 'edit_user' year=1 %}  # 标准的

# 有名分组反向解析
url(r'^edit_user_info/(\d+)', views.edit_user_info, name='edit_user')

# 后端解析
reverse('add', args=(12,))
reverse('add', kwargs={'year': 12})

Pseudo-code interpretation

url(r'^edit_user/(\d+)/',views.edit_user,names='edit')


{% for user_obj in user_queryset %}
    <a href="edit_user/{{ user_obj.id }}/">编辑</a>
    <a href="{% url 'edit' user_obj.id %}">编辑</a>
{% endfor %}


def edit_user(request,edit_id):
    reverse('edit',args=(edit_id,))

Route distribution

When django project is relatively large when the relationship between routing and view corresponding function more, total routing code is too lengthy, taking into account the total routing code is bad maintenance, django support each app can have its own urls.py.

And the total route no longer do a correspondence relationship with the view routing function, but only one operation only task distribution.

Depending on the request, identifying the current request requires access to the functions which belong to the app, and then automatically delivered to the corresponding app urls.py inside, and then do the matching route with the app view function inside urls.py.

不仅如此,每个app除了可以有自己的urls.py之外,还可以有自己的static静态资源文件夹,templates模板文件夹。

基于上面的特点,基于django分小组开发会变得额外的简单

每个人只需要开发自己的app即可,之后只需要创建一个空的django项目,将多个人的app全部拷贝到项目下,配置文件注册。

1、总路由

1.总路由
from django.conf.urls import url,include


# 路由分发  注意事项应用名后面千万不能加$
# from app01 import urls as app01_urls
# from app02 import urls as app02_urls
# url(r'^app01/',include(app01_urls)),
# url(r'^app02/',include(app02_urls))

# 简写
url(r'^app01/',include('app01.urls')),
url(r'^app02/',include('app02.urls'))

2、子路由

from django.conf.urls import url
from app01 import views

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

from django.conf.urls import url
from app02 import views

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

名称空间(了解)

url(r'^app01/',include('app01.urls',namespace='app01'))
url(r'^app02/',include('app02.urls',namespace='app02'))
后端解析
reverse('app01:index')
reverse('app02:index')
前端解析
{% url 'app01:index' %}
{% url 'app02:index' %}
# 在给路由与视图函数起别名的时候只需要保证永远不出现冲突的情况即可
# 通常情况下我们推荐期别名的时候加上当前应用的应用名前缀

url(r'^index/',views.index,name='app01_index')
url(r'^index/',views.index,name='app02_index')

虚拟环境

我们想做到针对不同的项目,只安装项目所需要的功能模块,项目用不到的一概不装,来避免加载资源时的消耗。

如何创建虚拟环境?利用pycharm的虚拟环境。此时的虚拟环境类似有一个新的python解释器。

Django版本区别

路由层:

1.x 用的是url

2.x、3.x用的是path

urlpatterns = [
    path('index/',views.index)
]

url第一个参数是一个正则表达式,而path第一参数不支持正则表达式,写什么就匹配什么。

如果觉得path不好用,2.x和3.x版本提供了一个跟url一样的功能:

re_path  # 等价于1.x版本里面的url功能

urlpatterns = [
    re_path(r'^index/',views.index)
]

虽然path不支持正则表达式,但是它给你提供了五种默认的转换器:

str,匹配除了路径分隔符(/)之外的非空字符串,这是默认的形式
int,匹配正整数,包含0。
slug,匹配字母、数字以及横杠、下划线组成的字符串。
uuid,匹配格式化的uuid,如 075194d3-6885-417e-a8a8-6c931e272f00。
path,匹配任何非空字符串,包含了路径分隔符(/)(不能用?)

path('login/<int:year>/',login

除了默认的五种转换器之外,还支持你自定义转换器

class MonthConverter:
regex='\d{2}' # 属性名必须为regex

def to_python(self, value):
    return int(value)

def to_url(self, value):
    return value # 匹配的regex是两个数字,返回的结果也必须是两个数字

伪静态

url以.html结尾,给人的感觉好像是这个文件是写死的,内容不会轻易的改变

作用:

为了提高网站的被搜索引擎收藏的力度,提供网站的SEO查询效率

但是,无论你怎么做优化,都玩不过RMB玩家

Guess you like

Origin www.cnblogs.com/cnhyk/p/12168196.html