gpt4 book ai didi

python - 使用选项创建自定义 Django CharField

转载 作者:太空宇宙 更新时间:2023-11-04 03:37:05 25 4
gpt4 key购买 nike

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

感谢您的帮助。

最佳答案

只需将 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)

关于python - 使用选项创建自定义 Django CharField,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28538082/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com