简体   繁体   中英

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. 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. If you are using the django admin for example, you can do something like (untested)

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

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