2014-12-26 175 views
1

我想過濾模型中的多對多字段。模型中的多對多字段的過濾器選擇django

class IdealBehaviour(models.Model): 
    cbs_role = models.ManyToManyField(CbsRole, null=True, blank=True) 
    cbs = models.ForeignKey('cbs.CBS', null=True, blank=True) 
    ideal_behaviour = models.CharField(max_length=500, null=True, blank=True) 
    Description = models.CharField(max_length=1000, null=True, blank=True) 
    created_time = models.DateTimeField(auto_now_add = True,null=True, blank=True) 

class StandardWork(models.Model): 
    cbs_and_role = models.ManyToManyField('userdata.CbsRole', null=True, blank=True) 
    standard_work_number = models.BigIntegerField(null=True, blank=True) 
    system_name= models.CharField(max_length=500, null=True, blank=True) 
    system_description=models.TextField(null=True, blank=True) 
    ideal_behaviour = models.ManyToManyField ('userdata.IdealBehaviour', null=True, blank=True) 
    publish = models.BooleanField(default=False) 
    created_time = models.DateTimeField(auto_now_add = True,null=True, blank=True) 

class TodoListForm(ModelForm): # used in manage view 
    class Meta: 
     model = StandardWork 
     exclude = ('publish', 'cbs_and_role', 'standard_work_number') 
     widgets = { 
       'system_description': forms.Textarea(attrs={'rows':3}), 
      } 

我想,因爲只有idealbehaviour顯示ideal_behaviour的選擇在TodoListForm查詢

cbsobject = CBS.objects.get(id=dat) 
idealbehaviour = IdealBehaviour.objects.filter(cbs=cbsobject) 

我想選擇的ideal_behaviour。

我如何查詢顯示理想行爲assosciated與該perticuler cbs只在modelform?

我得到了解決

def __init__(self, *args, **kwargs): 
     super(PollForm, self).__init__(*args, **kwargs) 
     if self.instance: 
      print "printing in form" 
      print self.instance.id 
      self.fields['ideal_behaviour'].queryset = IdealBehaviour.objects.filter(cbs__exact=self.instance.id) 

,但我不如何獲得CBS的ID。 self.instance.id提供標準作業ID。我想要cbs的id。即我想在形式上作爲一個實例的cbsobject。之後,它的工作正常。

回答

2

得到了解決方案。我不知道它的可行與否,但我把表格放在視圖文件中,所以我可以得到cbsobject的實例。

class PollForm(forms.ModelForm): # used in manage view 
        class Meta: 
         model = StandardWork 
         exclude = ('cbs_and_role','publish', 'standard_work_number') 
         widgets = { 
          'system_description': forms.Textarea(attrs={'rows':3}), 
         } 
        def __init__(self, *args, **kwargs): 
         super(PollForm, self).__init__(*args, **kwargs) 
         if self.instance: 
          print "printing in form" 
          print self.instance.id 
          self.fields['ideal_behaviour'].queryset = IdealBehaviour.objects.filter(cbs__exact=cbsobject) 

如果有更好的解決方案,請讓我知道。並請指導我這個接近這個詞的不好。謝謝。