使用选项创建自定义Django CharField

时间:2015-02-16 09:21:04

标签: python django

我在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')
    )

非常感谢您的帮助。

1 个答案:

答案 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)