Django_tips

1、Django的配置靜態文件(settings)

STATIC_URL = '/static/'    #引用名
STATICFILES_DIRS = (
    os.path.join(BASE_DIR,"statics"),  # 實際名 ,即實際文件夾的名字
)

django對引用名和實際名進行映射,引用時,只能按照引用名來,不能按實際名去找html

#<script src="/statics/jquery-3.1.1.js"></script>
#------error-----不能直接用,必須用STATIC_URL = '/static/':
#<script src="/static/jquery-3.1.1.js"></script>

推薦方式:前端

STATIC_URL = '/static/'
前端:
{% load staticfiles %}
<script src={% static "jquery-1.8.2.min.js" %}></script>

 2、Django URL(路由系統)

 一、url  --- 視圖

urlpatterns = [
    url(正則表達式, views視圖函數,參數,別名),
]
def url(regex, view, kwargs=None, name=None):

kwargs:傳給視圖的默認參數(字典形式)python

name:別名xxxjquery

好比:正則表達式

<form action="{% url 'xxx' %}" class="form-horizontal" method="post">

就能夠提交到該路由sql

路由一旦匹配成功就不匹配下面的url了,因此最好加上$結尾符django

二、無命名分組和有命名分組

url(r'^articles/([0-9]{4})/$', views.year_archive),  #no_named group
url(r'^articles/(?P<year>[0-9]{4})/$', views.year_archive),#named group

有命名分組的year爲視圖的關鍵字參數 app

注意:同源策略ide

三、路由分發

url(r'^article/',include(("article.urls","article"),namespace="article")),
def include(arg, namespace=None):
    app_name = None
    if isinstance(arg, tuple):
        # Callable returning a namespace hint.
        try:
            urlconf_module, app_name = arg
        except ValueError:
            if namespace:
                raise ImproperlyConfigured(
                    'Cannot override the namespace for a dynamic module that '
                    'provides a namespace.'
                )
            raise ImproperlyConfigured(
                'Passing a %d-tuple to include() is not supported. Pass a '
                '2-tuple containing the list of patterns and app_name, and '
                'provide the namespace argument to include() instead.' % len(arg)
            )
    else:
        # No namespace hint - use manually provided namespace.
        urlconf_module = arg

    if isinstance(urlconf_module, str):
        urlconf_module = import_module(urlconf_module)
    patterns = getattr(urlconf_module, 'urlpatterns', urlconf_module)
    app_name = getattr(urlconf_module, 'app_name', app_name)
    if namespace and not app_name:
        raise ImproperlyConfigured(
            'Specifying a namespace in include() without providing an app_name '
            'is not supported. Set the app_name attribute in the included '
            'module, or pass a 2-tuple containing the list of patterns and '
            'app_name instead.',
        )
    namespace = namespace or app_name
    # Make sure the patterns can be iterated through (without this, some
    # testcases will break).
    if isinstance(patterns, (list, tuple)):
        for url_pattern in patterns:
            pattern = getattr(url_pattern, 'pattern', None)
            if isinstance(pattern, LocalePrefixPattern):
                raise ImproperlyConfigured(
                    'Using i18n_patterns in an included URLconf is not allowed.'
                )
    return (urlconf_module, app_name, namespace)
View Code
url(r'^article/',include(("appxxx.urls","app_name"),namespace="appxxx")),

app_name和namespace區別參考https://www.jianshu.com/p/404500a0408a  函數

3、Django views(視圖函數)

 django.http中有兩個重要的對象HttpRequest、HttpResponse

注意一個經常使用的方法:request.POST.get('')

4、模板語法

HTML代碼+邏輯控制代碼

一、變量 --- {{ xxx }}

①深度變量的查找 ---萬能的句點號

[1]、訪問列表索引 {{ items.2 }}

[2]、訪問字典的值 {{ person.name }}

[3]、訪問對象的屬性 {{ date.year }} date=datetime.date(1993,5,2)

[4]、訪問自定義類對象的屬性 {{ person.firstname }}

[5]、引用對象的方法 {{ var.upper }} ---注意:只能調用不須要參數的方法

②變量的過濾器 ---filter

語法格式:      {{ obj | filter:param }}

 # 1  add          :   給變量加上相應的值
   #
   # 2  addslashes   :    給變量中的引號前加上斜線
   #
   # 3  capfirst     :    首字母大寫
   #
   # 4  cut          :   從字符串中移除指定的字符
   #
   # 5  date         :   格式化日期字符串
   #
   # 6  default      :   若是值是False,就替換成設置的默認值,不然就是用原本的值
   #
   # 7  default_if_none:  若是值是None,就替換成設置的默認值,不然就使用原本的值


#實例:

#value1="aBcDe"
{{ value1|upper }}<br>

#value2=5
{{ value2|add:3 }}<br>

#value3='he  llo wo r ld'
{{ value3|cut:' ' }}<br>

#import datetime
#value4=datetime.datetime.now()
{{ value4|date:'Y-m-d' }}<br>

#value5=[]
{{ value5|default:'空的' }}<br>

#value6='<a href="#">跳轉</a>'

{{ value6 }}

{% autoescape off %}
  {{ value6 }}
{% endautoescape %}

{{ value6|safe }}<br>

{{ value6|striptags }}

#value7='1234'
{{ value7|filesizeformat }}<br>
{{ value7|first }}<br>
{{ value7|length }}<br>
{{ value7|slice:":-1" }}<br>

#value8='http://www.baidu.com/?a=1&b=3'
{{ value8|urlencode }}<br>
    value9='hello I am yuan'
View Code

 二、標籤(tag) ---{% tags %}

①{% if %}

②{% for %}

不支持break,也不支持continue,但內置了一個forloop變量,forloop.counter---計數從1開始

③{% csrf_token %}

注意:使用render_to_response方法,不會生效

④{% url %}

⑤{% with total=gjdgfdlkgjkdjgjgisdgdsg %}{{ total }}{% endwith %}

⑥{% verbatim %} ---禁止render

⑦{% load %}

三、自定義filter和simple_tag

①在app中建立templatetags模塊(必須的)

②建立任意 .py 文件,如:my_tags.py

from django import template
from django.utils.safestring import mark_safe

register = template.Library()   #register的名字是固定的,不可改變


@register.filter
def filter_multi(v1,v2):
    return  v1 * v2


@register.simple_tag
def simple_tag_multi(v1,v2):
    return  v1 * v2


@register.simple_tag
def my_input(id,arg):
    result = "<input type='text' id='%s' class='%s' />" %(id,arg,)
    return mark_safe(result)
View Code

③在使用自定義simple_tag和filter的html文件中導入以前建立的 my_tags.py :{% load my_tags %}

④使用simple_tag和filter(如何調用)

-------------------------------.html
{% load xxx %}   #首行
    
    
    
    
 # num=12
{{ num|filter_multi:2 }} #24

{{ num|filter_multi:"[22,333,4444]" }}


{% simple_tag_multi 2 5 %}  參數不限,但不能放在if for語句中
{% simple_tag_multi num 5 %}
View Code

⑤在settings中的INSTALLED_APPS配置當前app,否則django沒法找到自定義的simple_tag.

注意:

filter能夠用在if等語句後,simple_tag不能夠

{% if num|filter_multi:30 > 100 %}
    {{ num|filter_multi:30 }}
{% endif %}
View Code

四、include和extends

①{% include xxx %}

②{% extends xxx %} ---必須在首行

{% block xxx %}{% endblock %}

注:{{ block.super }}在上級代碼塊基礎上添加內容

5、Models

django.db.models.Model類

關係:一對一(foreign key + unique) 、一對多(foreign key)、多對多(兩個foreign key),外鍵默認關聯的是主鍵

注:關於 Class Meta用法可參考https://blog.csdn.net/qq_41763291/article/details/80229977http://iluoxuan.iteye.com/blog/1703061

一、模型經常使用的字段類型參數

①CharFiled等,參考http://www.cnblogs.com/wt869054461/p/4014271.html

二、Filed重要參數

參考①連接

三、表的操做(增刪改查)

①增

from app01.models import *

    #create方式一:   Author.objects.create(name='Alvin')

    #create方式二:   Author.objects.create(**{"name":"alex"})

    #save方式一:     author=Author(name="alvin")
                    author.save()

    #save方式二:     author=Author()
                    author.name="alvin"
                    author.save()

如下表名的意思爲models中的類名

[1]、一對多關係

能夠直接用 外鍵字段_id    如 表名.objects.create(外鍵字段_id=2,...)  綁定外鍵表當中id=2的行對象 

[2]、多對多

A、第三張表經過models.ManyToManyField()建立的

a、正向添加:

     外鍵表對象f1=外鍵表名.objects.get(id=1)

     外鍵表對象f2=外鍵表名.objects.get(id=2)

     表對象obj=表名.objects.get(id=1)

     obj.外鍵字段.add(f1,f2)    ---等同於 obj.外鍵字段.add(*[f1,f2])  

b、反向添加:

     表對象obj=表名.objects.get(id=1)

     外鍵表對象f=外鍵表名.objects.get(id=2)

     f.表名小寫_set.add(obj)

也就是說  表對象obj.外鍵字段.add(xxx)   也能夠   外鍵表對象f.表名小寫_set.add(obj)

B、第三張表本身建立的

相似於一對多的方式

②刪

delete()  ---級聯刪除

多對多關係

remove()、clear()

③改

update()爲QuerySet對象的方法

save()更新全部列,效率低,而update()只更新更改的列

多對多的更改,先清空clear()再添加add(xxx)

④查

filter、all、get---沒有匹配的報錯、values---字典、value_list---元組

四、QuerySet惰性機制

只有當調用QuerySet時才執行sql

cache避免重複查詢

iterator()適合操做大的queryset,節省內存,但需重複遍歷

五、對象查詢、單表條件查詢,多表條件關聯查詢

#--------------------對象形式的查找--------------------------
    # 正向查找
    ret1=models.Book.objects.first()
    print(ret1.title)
    print(ret1.price)
    print(ret1.publisher)
    print(ret1.publisher.name)  #由於一對多的關係因此ret1.publisher是一個對象,而不是一個queryset集合

    # 反向查找
    ret2=models.Publish.objects.last()
    print(ret2.name)
    print(ret2.city)
    #如何拿到與它綁定的Book對象呢?
    print(ret2.book_set.all()) #ret2.book_set是一個queryset集合

#---------------了不得的雙下劃線(__)之單表條件查詢----------------

#    models.Tb1.objects.filter(id__lt=10, id__gt=1)   # 獲取id大於1 且 小於10的值
#
#    models.Tb1.objects.filter(id__in=[11, 22, 33])   # 獲取id等於十一、2二、33的數據
#    models.Tb1.objects.exclude(id__in=[11, 22, 33])  # not in
#
#    models.Tb1.objects.filter(name__contains="ven")
#    models.Tb1.objects.filter(name__icontains="ven") # icontains大小寫不敏感
#
#    models.Tb1.objects.filter(id__range=[1, 2])   # 範圍bettwen and
#
#    startswith,istartswith, endswith, iendswith,

#----------------了不得的雙下劃線(__)之多表條件關聯查詢---------------

# 正向查找(條件)

#     ret3=models.Book.objects.filter(title='Python').values('id')
#     print(ret3)#[{'id': 1}]

      #正向查找(條件)之一對多

      ret4=models.Book.objects.filter(title='Python').values('publisher__city')
      print(ret4)  #[{'publisher__city': '北京'}]

      #正向查找(條件)之多對多
      ret5=models.Book.objects.filter(title='Python').values('author__name')
      print(ret5)
      ret6=models.Book.objects.filter(author__name="alex").values('title')
      print(ret6)

      #注意
      #正向查找的publisher__city或者author__name中的publisher,author是book表中綁定的字段
      #一對多和多對多在這裏用法沒區別

# 反向查找(條件)

    #反向查找之一對多:
    ret8=models.Publisher.objects.filter(book__title='Python').values('name')
    print(ret8)#[{'name': '人大出版社'}]  注意,book__title中的book就是Publisher的關聯表名

    ret9=models.Publisher.objects.filter(book__title='Python').values('book__authors')
    print(ret9)#[{'book__authors': 1}, {'book__authors': 2}]

    #反向查找之多對多:
    ret10=models.Author.objects.filter(book__title='Python').values('name')
    print(ret10)#[{'name': 'alex'}, {'name': 'alvin'}]

    #注意
    #正向查找的book__title中的book是表名Book
    #一對多和多對多在這裏用法沒區別

六、聚合查詢和分組查詢

aggregate()、annotate()

七、F查詢和Q查詢

 

本文參考文獻:https://www.cnblogs.com/yuanchenqi/articles/6083427.html

相關文章
相關標籤/搜索
本站公眾號
   歡迎關注本站公眾號,獲取更多信息