简体   繁体   中英

How do I set a Dynamic Choice Field using a Model field in Django

How can I use 'Dynamic Choices' generated from another Model field? I would like to add a new choice to a field called color without editing code/tuple. The example below demonstrations what I have already tried, but in this example 'choices' doesn't expect a model to be used so this will not work! Is this possible, if so what would be the best approach?

class Furniture(models.Model):
     color = models.CharField(max_length=50, choices=FurnitureChoices)


class FurnitureChoices(models.Model):
      color = models.CharField(max_length=50)

It is not the FK to the model I'm interested in, but the ability to allow users to add additional choices themselves.

You can do this with ForeignKey.

class Furniture(models.Model):
     color = models.ForeignKey(FurnitureChoices)


class FurnitureChoices(models.Model):
      color = models.CharField(max_length=50)

Or you can do something like this:

class FurnitureChoices(models.Model):
    COLOR_CHOICES = (
        ('R', 'Red'),
        ('B', 'Blue'),
     )
    color = models.CharField(max_length=1, choices=COLOR_CHOICES)

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