我在models.py
文件中有以下代码:
SENT = 0
ACEPTED = 1
DECLINED = 2
SHARE_STATUSES = (
(SENT, 'Sent'),
(ACCEPTED, 'Approved'),
(DECLINED, 'Declined')
)
status = models.ResultStatusField(max_length=2, choices=STATUS_CHOICES, default=SENT)
我想创建一个带有选项的自定义Django字段类型(可以在整个应用程序模块中重用,而不是在不同的地方多次复制粘贴)。
我已经阅读了关于如何创建自定义字段的Django reference,但不了解如何提供选择。
class ResultStatusField(models.CharField):
def __init__(self):
SENT = 0
ACCEPTED = 1
DECLINED = 2
SHARE_STATUSES = (
(SENT, 'Sent'),
(ACCEPTED, 'Approved'),
(DECLINED, 'Declined')
)
非常感谢您的帮助。
答案 0 :(得分:2)
只需将choices
添加到关键字参数:
class ResultStatusField(models.CharField):
def __init__(self, *args, **kwargs):
SENT = 0
ACCEPTED = 1
DECLINED = 2
SHARE_STATUSES = (
(SENT, 'Sent'),
(ACCEPTED, 'Approved'),
(DECLINED, 'Declined')
)
kwargs['choices'] = SHARE_STATUSES
kwargs['default'] = SENT
kwargs['max_length'] = 2
super(ResultStatusField, self).__init__(*args, **kwargs)