[英]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.