首页 » 编程开发 » Python » 正文

Django在Model中枚举ENUM表字段创建的例子——PYTHON

本文介绍Django开发中通过model创建MYSQL数据库中包含ENUM枚举类型字段的表,方法如下:

from django.db import models

class EnumField(models.Field):
def __init__(self, *args, **kwargs):
super(EnumField, self).__init__(*args, **kwargs)
assert self.choices, “Need choices for enumeration”

def db_type(self, connection):
if not all(isinstance(col, basestring) for col, _ in self.choices):
raise ValueError(“MySQL ENUM values should be strings”)
return “ENUM({})”.format(‘,’.join(“‘{}'”.format(col)
for col, _ in self.choices))
class IceCreamFlavor(EnumField, models.CharField):
def __init__(self, *args, **kwargs):
flavors = [(‘chocolate’, ‘Chocolate’),
(‘vanilla’, ‘Vanilla’),
]
super(IceCreamFlavor, self).__init__(*args, choices=flavors, **kwargs)
class IceCream(models.Model):
price = models.DecimalField(max_digits=4, decimal_places=2)
flavor = IceCreamFlavor(max_length=20)

运行“python manage.py syncdb”,检查一下数据库中的表,看ENUM枚举字段是否成功创建了。

mysql>SHOW COLUMNS IN icecream;
+——–+—————————–+——+—–+———+—————-+
| Field | Type | Null | Key | Default | Extra |
+——–+—————————–+——+—–+———+—————-+
| id | int(11) | NO | PRI | NULL | auto_increment |
| price | decimal(4,2) | NO | | NULL | |
| flavor | enum(‘chocolate’,’vanilla’) | NO | | NULL | |
+——–+—————————–+——+—–+———+—————-+

Django开发中,MYSQL表中ENUM类型字段的创建方法就是上面这样了,不过,在这里提醒一句,对于后面可能会需要修改的字段,最后还是不要用ENUM类型,因为要修改将会非常困难,还是用TINYINT代替比较简单。

发表评论