[英]How to set models choices dynamicly in Django
首先请看下面我的代码:
Project = models.ForeignKey(Project,null=False, blank=True)
if Porject is 'A':
Owner = models.CharField(max_length=100, choices=**owner_set_A**)
else:
Owner = models.CharField(max_length=100, choices=**owner_set_B**)
因此,所有者的选择应从owner_set_A切换到B,这取决于Project的值。 我告诉谁我该怎么做,谢谢蒂米的答复,但我应该在模型中做什么。
class Task(models.Model):
project = models.ForeignKey(Project,null=False, blank=True)
if Porject is 'A':
Owner = models.CharField(max_length=100, choices=**owner_set_A**)
else:
Owner = models.CharField(max_length=100, choices=**owner_set_B**)
有没有一种方法来获取项目字段值?
您不需要两个单独的字段。 本场只保存数据,而不是你需要过滤什么choices
用户在他们的形式呈现。 例如,如果您使用的是django管理员,则可以执行类似(未测试)的操作
class MyModelForm(forms.ModelForm):
def __init__(self, *args, *kwargs):
super(MyModel, self).__init__(args, kwargs)
if self.fields['project'].foo == "bar":
self.fields['owner'].choices = ((0, "X"), (1, "Y"),...)
else:
self.fields['owner'].choices = ((0, "A"), (1, "B"),...)
class Meta:
model = MyModel
管理员
class MyModelAdmin(admin.ModelAdmin):
form = MyModelForm
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.