简体   繁体   中英

Subclassing the Models.Charfield for my Own Custom model Field

I want a custom Field called Status, that foreinkey's in another model Reading the doc's 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'

I don't know if I am going after it the right way, Basically I want to change the status of a transaction, from Initiated>Accepted>Delivered>|canceled

It doesn't seem that you need to create a custom field at all. Just use regular CharField with choices and default , for example:

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

Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM