[英]Django CharField with choices, auto add possible choices to database on syncdb or migrate?
我知道有一种方法可以自动将值添加到syncdb(即Fixtures)上的数据库中。 但是我在想,也许有一种方法可以检测这些选择,并在syncdb上的数据库上自动创建这些选择数量,或者进行迁移。
我想要这个的原因:
SERVICE_TYPES = (
("SALE", _("Sale")),
("RENT", _("Rent"))
)
class ServiceType(models.Model):
type_of_service = models.CharField(_("Type of service"), choices=SERVICE_TYPES, default=SERVICE_TYPES[0][0], max_length=20)
class Meta:
verbose_name = "Service Type"
verbose_name_plural = "Services Types"
def __str__(self):
pass
class Service(models.Model):
service_type = models.ForeignKey(ServiceType)
product_family = models.ManyToManyField(ProductFamily)
class Meta:
verbose_name = "Service"
verbose_name_plural = "Services"
def __str__(self):
pass
我希望在syncdb上,ServiceType自动在数据库上生成两个可能的选择,因此我可以添加具有可用的Sale和Rent选项的服务。
您可以创建一个遍历SERVICE_TYPES
的数据迁移,并确保ServiceType
表反映了这一点。 您可以在此处查看如何执行此操作: https : //docs.djangoproject.com/en/1.8/topics/migrations/#data-migrations
您确定不想直接将type_of_service
为Service
的属性吗? 如果您不打算向ServiceType
添加额外的属性,那将是最有意义的。 如果您要为不同类型的服务添加额外的属性,我宁愿为每种类型的服务创建一个不同的子类。
是的,您可以将其添加到模型中:
SERVICE_TYPES = (
('sale', 'Sale'),
('rent', 'Rent')
)
service_type=models.CharField(max_length=50, null=False, blank=False, choices=SERVICE_TYPES)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.