目录

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

    admin.py

    # -*- 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

    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

    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

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

    admin.py

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

    4. Model 中 Choices 使用

    # -*- 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

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

    console 中

    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. 字符串与时间相互转换

    • 将字符串转换为时间对象
    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)
    
    • 将时间对象转换为字符串
    from datetime import datetime
    print datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    '2017-09-30 09:50:57'
    

    6. 组装装饰器

    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