Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
262 views
in Technique[技术] by (71.8m points)

python - Django: Best way to implement "status" field in modules

I have a field in my module that is used to hold the status of the object. So far I have used:

ORDER_STATUS = ((0, 'Started'), (1, 'Done'), (2, 'Error'))
status = models.SmallIntegerField(choices=ORDER_STATUS)

Its easy to convert one way:

def status_str(self): return ORDER_STATUS[self.status][1]

The problem is when updating. I find myself having code like this:

order.status = 2 # Error Status

Which is quite awful and gets really hard to synchronize. I guess a solution would be something similar to C's enum{}. Or perhaps there is a whole different way to tackle this problem ?

Thanks

question from:https://stackoverflow.com/questions/2142055/django-best-way-to-implement-status-field-in-modules

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Maybe this question helps you: Set Django IntegerField by choices=… name.
I quote from the accepted answer (with adjustments ;)):
Put this into your class (STATUS_CHOICES will be the list that is handed to the choices option of the field):

PENDING = 0
DONE = 1
STATUS_CHOICES = (
    (PENDING, 'Pending'),
    (DONE, 'Done'),
)

Then you can do order.status = Order.DONE.


Note that you don't have to implement an own method to retrieve the (readable) value, Django provides the method get_status_display itself.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...