2016-10-28 147 views
0

對不起,如果標題沒有多大意義。django:如何從m2m字段的入口選擇字段進行選擇?

比方說,我們有一個模型建立這樣的:

class Sample(models.Model): 
    name = models.CharField(max_length=300) 
    def __str__(self): 
     return self.name 

class Project(models.Model): 
    description = models.CharField(max_length = 200, null=True) 
    sample = models.ManyToManyField(Sample) 

class SampleLogoutRecord(models.Model): 
    project = models.ForeignKey(Project, on_delete = models.CASCADE, null=True) 
    sample_choice = models.CharField(max_length = 200, null=True, choices = SAMPLE_CHOCIES) 
    logout_date = models.DateField(null=True) 
    logout_by = models.CharField(max_length = 200, null=True) 

所以基本上與具有持有,涉及到幾個樣本用於M2M領域樣品的主力車型項目。然後SampleLogoutRecord是項目的外鍵,它是屬於該項目的特定樣本的記錄被註銷。我的問題是,我如何設置sample_choice,以便該選擇字段使用屬於此項目的樣本作爲選項?

例如,如果項目A樣品1,2和3。我想sample_choice要與選項的選擇領域:1,2和3

從官方文件似乎是一個選擇的選擇字段可以是一個可返回的2元組列表。這聽起來像我應該做的,但我被困在實際上如何實現這一點。

TIA

回答

0

在窗體的init方法,從數據庫中值填充選擇:

class SampleLogoutRecordForm(forms.ModelForm): 

    def __init__(self, project, args, **kwargs): 
     super(SampleLogoutRecordForm, self).__init__(*args, **kwargs) 
     self.fields['sample_choice'].choices = [ 
      (x.id, x.name) for x in project.sample.all() 
     ] 
     self.project = project 

    def save(self, *args, **kwargs): 
     """ Assign the project here """ 
     logout_record = super(SampleLogoutRecordForm, self).save(*args, **kwargs, commit=False) 
     logout_record.project = self.project 
     logout_record.save() 
     return logout_record 

    class Meta: 
     model = Article 
     fields = ['sample_choice', 'logout_date', 'logout_by'] 

在您看來,實例化形式的額外project參數,包括POST請求處理位。

if request.method == 'POST': 
    form = SampleLogoutRecordForm(project, request.POST) 
    if form.is_valid(): 
     record = form.save() 
     # now do stuff to redirect 
else: 
    form = SampleLogoutRecordForm(project)