[英]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. 我想在不编辑代码/元组的情况下向
color
字段添加新选择。 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. 我感兴趣的模型不是FK,而是允许用户自己添加其他选择的功能。
You can do this with ForeignKey. 您可以使用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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.