简体   繁体   中英

Django CharField with choices, auto add possible choices to database on syncdb or migrate?

I know there is a way to automatically add values to database on syncdb, which is Fixtures. But I was thinking maybe there's a way to detect the choices and automatically create those number of choices on database on syncdb or migrate.

The reason why I want this:

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

I would like that, on syncdb, the ServiceType automatically generates the two possible choices on database, so then I can add services with the Sale and Rent choices available.

You can create a data migration that loops through SERVICE_TYPES and makes sure that the table for ServiceType reflects that. You can see how you can do that here: https://docs.djangoproject.com/en/1.8/topics/migrations/#data-migrations

Are you sure you don't want to make type_of_service an attribute on Service directly? It makes the most sense if you aren't going to add extra attributes to ServiceType . If you are going to add extra attributes for different types of services, I'd rather create a different subclass for each type of service.

Yes, you can add this to the model:

SERVICE_TYPES = (
    ('sale', 'Sale'),
    ('rent', 'Rent') 
)
service_type=models.CharField(max_length=50, null=False, blank=False, choices=SERVICE_TYPES)

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