为我自己的自定义模型字段子类化Models.Charfield

时间:2014-03-12 19:24:17

标签: python django

我想要一个名为Status的自定义字段,即foreinkey在另一个模型中 阅读文档的https://docs.djangoproject.com/en/dev/howto/custom-model-fields/

1class TransactionStateModelField(models.CharField):
    description = 'What state is this transaction'

    def __init__(self, *args, **kwargs):
        kwargs['status'] = 'initiated' # additional options for status could be accepted and delivered
        super(TransactionStateModelField, self).__init__(*args, **kwargs)

2:11:42 web.1  |   File "/home/talisman/virt_env/tempilo/local/lib/python2.7/site-packages/Django-1.5.4-py2.7.egg/django/db/models/fields/__init__.py", line 626, in __init__
12:11:42 web.1  |     super(CharField, self).__init__(*args, **kwargs)
12:11:42 web.1  | TypeError: __init__() got an unexpected keyword argument 'status'

我不知道我是否正确地追求它, 基本上我想更改交易的状态,从已启动>已接受>已交付> |已取消

1 个答案:

答案 0 :(得分:3)

您似乎根本不需要创建自定义字段。只需使用常规CharFieldchoicesdefault,例如:

from django.db import models

class MyModel(models.Model):
    STATUSES = (
        ('i', 'Initiated'),
        ('a', 'Accepted'),
        ('d', 'Delivered'),
        ('c', 'Cancelled'),
    )
    status = models.CharField(choices=STATUSES, default='i')

希望有所帮助。