简体   繁体   English

如何在Django中动态设置模型选择

[英]How to set models choices dynamicly in Django

First please have a look at my code below: 首先请看下面我的代码:

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**)

So the owner choices should switch from owner_set_A to B, it depense on the value of Project. 因此,所有者的选择应从owner_set_A切换到B,这取决于Project的值。 Who i tell me how can i do this, Thanks for Timmy's reply, but what should i do in models.Model 我告诉谁我该怎么做,谢谢蒂米的答复,但我应该在模型中做什么。

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**)

Is there a way to get the project field value? 有没有一种方法来获取项目字段值?

You don't need two separate fields. 您不需要两个单独的字段。 The field just holds the data, you instead need to filter what choices the user is presented with in their form. 本场只保存数据,而不是你需要过滤什么choices用户在他们的形式呈现。 If you are using the django admin for example, you can do something like (untested) 例如,如果您使用的是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

admin.py 管理员

class MyModelAdmin(admin.ModelAdmin):
    form = MyModelForm

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM