Skip to content

ramwin/django-reference

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

A quick reference for django the test project is in rest-framework-test repository

官网文档

FAQ

Databases and models

  • How can I see the raw SQL queries Django is running? 查看queryset的sql语句 使用connection.queries
DEBUG模式
from django.db import connection
connection.queires
from djabgo.db import reset_queries
reset_queries()  # 清空query

或者使用print(queryset.query) queryset.query.sql_with_params() stackoverflow链接

Topic guides

讨论各种主题和工具 at a fairly high level, 提供一些背景知识和解释

Models and databases

Model & Queryset

./queryset.md
./advanced.md
./pagination.md

Django The Model Layer 数据库model层 官网

Model & Field

Migrations

Data Migrations 数据迁移

python manage.py makemigrations --empty yourappname
from django.db import migrations
def combine_names(apps, schema_editor):
    Person = apps.get_model("yourappname", "Person")
    for person in Person.objects.all():
        person.name = "%s %s" % (person.first_name, person.last_name)
        person.save()
class Migration(migrations.Migration):
    dependencies = [
        ("yourappname", "0001_initial"),
    ]
    operations = [
        migrations.RunPython(combine_names, reverse_code=migrations.RunPython.noop)
    ]

TODO list

  • Model Instance
  • Other
./views.md

Request and Response

./request_response.md
  • attribute
    • errors 具体的报错信息
    f.errors
    {'sender': ['Enter a valid email address.'], 'subject': ['This field is required.']}
    
  • method
    • clean() 其实就是调用了clean_data

Built-in fields

  • FileField

开发进程 Development Process

官网

Settings配置

./settings.md
  • Applications

    • Configuring applications
    from django.apps import AppConfig
    class MyAppConfig(AppConfig):
        verbose_name = "自己的名字"
    注意修改后要在 app/__init__.py 里面设置 default_app_config = 'app.apps.MyAppConfig'
    
  • Exceptions
    Django Core Exceptions
    from django.core.exceptions import *

    • ValidationError()
    • ObjectDoesNotExist 因为model.DoesNotExist是继承了这个Exception, 所以可以用一个ObjectDoesNotExist来判断多个错误
    from django.core.exceptions import ObjectDoesNotExist
    try:
        e = Entry.objects.get(id=3)
        b = Blog.objects.get(id=1)
    except ObjectDoesNotExist:
        print("Either the entry or blog doesn't exist.")
    
    • model.DoesNotExist from django.core.exceptions import ObjectDoesNotExist
    • MultipleObjectsReturned
    • PermissionDenied()

django-admin and manage.py

./available_commands.md
./customcommand.md
from django.core.management import call_command

Testing 测试

:maxdepth: 5
./test测试.md

Deployment 部署

WSGI servers, uwsgi

./uwsgi部署.md

gunicorn

./gunicorn.md

信号的处理机制

  • signal绑定的情况下
    • 如果是runserver的进程, term的时候会直接崩溃
    • 如果是gunicorn的进程, term的时候也会直接崩溃
  • 没有signal绑定的情况下
    • 如果是gunicorn的进程, 会先启动新的进程, term的时候会等待最后一个请求完成

form表单提交的csrf数据: csrfmiddlewaretoken="wfjdaefefewajfklajsf"

    from django.views.decorators.csrf import csrf_exempt
    @csrf_exempt
    def view(request):
        return HttpResponse('csrf')
  • Time zones 时区
./timezone时区.md
from django.utils.encoding import python_2_unicode_compatible
from __future__ import unicode_literals
./logging.md

Serialization

from django.core import serializers
serializers.serializer("json", Iterable[Model], indent=4)  # json字符串

Authentication Permission

cache 缓存系统,

官网

from django.core.cache import cache
from django.core.cache import caches

cache.set('foo', 'bar', timeout=3600)
cache = caches['thirdparty']
cache.set('foo', 'bar', timeout=3600*24*60)
cache.get('cache_list', [])  # 没有默认值就返回None
from django.core.pagiator import Paginator
objects = Model.objects.all()
p = Paginator(objects, 2)   # 每页显示2个元素
p.count # 获取一共多少个元素
p.num_pages # 获取页数
objectslist = p.page(n)   # 获取第n页
objectslist.has_previous | has_next # 判断是否有下一页
objectslist.previous_page_number | next_page_number # 获取上一页或下一页的页码
objectslist.number  # 当前页码

Data Validation

./validator表单验证.md
  • The ContentType Model
    • app_label: application的名字.如果有层import,就是最后的路径
    • model: model的name
    • name: 人看的name
  • ContentType的方法
    • [ ]
    • model_class(): 返回contenttype对应的model
    class ContentType(models.Model):
        def model_class(self):
            try:
                return apps.get_model(self.app_label, self.model)
            except LookupError:
                return None
    
  • ContentTypeManager
    • [ ]
    • get_for_model(model)
    ContentType.objects.get_for_model(User)
    
    • [ ]

TODO list

  • 生成随即的字符串
from django.utils.crypto import get_random_string
get_random_string(length=6)