Django Snippets

2023年 1月 4日 50.6k 0

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

相关文章

KubeSphere 部署向量数据库 Milvus 实战指南
探索 Kubernetes 持久化存储之 Longhorn 初窥门径
征服 Docker 镜像访问限制!KubeSphere v3.4.1 成功部署全攻略
那些年在 Terraform 上吃到的糖和踩过的坑
无需 Kubernetes 测试 Kubernetes 网络实现
Kubernetes v1.31 中的移除和主要变更

发布评论