惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园 - 聂微东
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
月光博客
月光博客
博客园 - 三生石上(FineUI控件)
The Cloudflare Blog
博客园 - Franky
IT之家
IT之家
V
Visual Studio Blog
博客园 - 【当耐特】
阮一峰的网络日志
阮一峰的网络日志
V
V2EX
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园 - 司徒正美
爱范儿
爱范儿
Hugging Face - Blog
Hugging Face - Blog
宝玉的分享
宝玉的分享
博客园 - 叶小钗
有赞技术团队
有赞技术团队
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
酷 壳 – CoolShell
酷 壳 – CoolShell
量子位
罗磊的独立博客
小众软件
小众软件
Jina AI
Jina AI

陈少文的网站

巨变与机遇的未来十年 Kubernetes 平台管理软件压力测试方案 使用镜像部署 Hexo 静态页面 终于等到你 - GitHub 镜像仓库服务(ghcr.io) 一起来学 Go --(6)Interface 一起来学 Go --(5)Goroutine 和 Channel 什么是函数式编程 如何在 Kubernetes 集群集成 Kata 柯里化与偏函数 使用 PyGithub 自动创建 Label 软件产品是团队能力的输出 Helm 2 、Helm 3 比较 IoT 变现 Kubernetes 中的 DNS 服务 国内的 Helm 镜像源 Harbor 使用自签证书支持 Https 访问 DevOps 工具链之 Prow 如何使用 kfctl 安装 Kubeflow VS Code 无法下载 Go 插件的工具包 工程师更应具有服务精神 你不知道的 Docker 使用技巧 使用 Docker 运行 Tensorflow 论中国 什么是左移 如何清空 Git 仓库全部历史记录 一禅小和尚 有风吹过厨房 时间的玫瑰 如何在 CentOS 安装 GPU 驱动 开发 Tips(19)
Django Snippets
微信公众号 · 2017-06-23 · via 陈少文的网站

1. Admin 自动注册全部 Model 字段

admin.py

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
# -*- coding: utf-8 -*-
import inspect
from django.contrib import admin
from . import models
for name, obj in inspect.getmembers(models):
    try:
        if inspect.isclass(obj):
            admin.site.register(getattr(models, name))
    except Exception as e:
        pass

2. 获取全部 View Name

获取 Project 全部 View Name

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
from django.conf import settings
from django.core.urlresolvers import RegexURLResolver, RegexURLPattern

root_urlconf = __import__(settings.ROOT_URLCONF)
all_urlpatterns = root_urlconf.urlpatterns
VIEW_NAMES = [] # maintain a global list

def get_all_view_names(urlpatterns):
    global VIEW_NAMES
    for pattern in urlpatterns:
        if isinstance(pattern, RegexURLResolver):
            get_all_view_names(pattern.url_patterns) # call this function recursively
        elif isinstance(pattern, RegexURLPattern):
            view_name = pattern.callback.func_name # get the view name
            VIEW_NAMES.append(view_name) # add the view to the global list
    return VIEW_NAMES

get_all_view_names(all_urlpatterns)

获取 App 全部 View Name

1
2
3
from my_app.urls import urlpatterns as my_app_urlpatterns

my_app_views = get_all_view_names(my_app_urlpatterns)

3. Admin 中 ManyToMany Field 支持搜索

models.py

1
2
class SomeModel(models.Model):
    users = models.ManyToMany(User)

admin.py

1
2
class SomeModelAdmin(admin.ModelAdmin):
    filter_horizontal = ('users',)

4. Model 中 Choices 使用

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# -*- coding: utf-8 -*-
from enum import Enum

class ChoiceEnum(Enum):
    @classmethod
    def choices(cls):
        return tuple((x.name, x.value) for x in cls)

    @classmethod
    def choices_name(cls):
        return tuple(x.name for x in cls)

    @classmethod
    def choices_value(cls):
        return tuple(x.value for x in cls)

    @classmethod
    def get_name(cls, value):
        if value in cls.choices_value():
            return cls.choices_name()[cls.choices_value().index(value)]
        else:
            return ''

    @classmethod
    def get_value(cls, name):
        if name in cls.choices_name():
            return cls.choices_value()[cls.choices_name().index(name)]
        else:
            return ''

class Colors(ChoiceEnum):
    RED = 'red'
    WHITE = 'white'
    BLUE = 'blue'

models.py

1
2
class Desk(models.Model):
    color = models.CharField(max_length=32, choices=Colors.choices(), default=Colors.RED.name)

console 中

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
print Colors.choices()
(('BLUE', 'blue'), ('RED', 'red'), ('WHITE', 'white'))

print Colors.RED.value
red

print Colors.get_name(Colors.RED.value)
RED

print Colors.choices_value()
('blue', 'red', 'white')

print Colors.choices_name()
('BLUE', 'RED', 'WHITE')

5. 字符串与时间相互转换

  • 将字符串转换为时间对象
1
2
3
from datetime import datetime
print datetime.strptime('2017-09-02 17:41:20', '%Y-%m-%d %H:%M:%S')
datetime.datetime(2017, 9, 2, 17, 41, 20)
  • 将时间对象转换为字符串
1
2
3
from datetime import datetime
print datetime.now().strftime('%Y-%m-%d %H:%M:%S')
'2017-09-30 09:50:57'

6. 组装装饰器

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
def compose_decorators(*funs):
    """
    按照顺序组装装饰器
    @A
    @B
    @C
    等价于
    @compose_decorators(A, B,C)
    """
    def deco(f):
        for fun in reversed(funs):
            f = fun(f)
        return f
    return deco