0

首先请看我下面的代码:

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 的值。谁告诉我我该怎么做,谢谢蒂米的回复,但是我应该在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**)

有没有办法获取项目字段值?

4

1 回答 1

1

您不需要两个单独的字段。该字段仅包含数据,您需要过滤choices用户在其表单中呈现的内容。例如,如果您使用 django admin,您可以执行类似(未经测试)的操作

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

管理员.py

class MyModelAdmin(admin.ModelAdmin):
    form = MyModelForm
于 2012-11-24T13:35:50.843 回答