筛选模型形式django中多对多字段的选项

时间:2014-12-26 04:48:32

标签: python django django-forms

我想在模型中过滤多个到多个字段。

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}),
            } 

我想为查询显示ideal_behaviour的选项

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

我想在TodoListForm中选择ideal_behaviour作为理想行为。

我如何查询以仅在模型中显示与该perticuler cbs相关的理想行为?

我得到了解决方案

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我希望在形式上作为一个实例。之后它的工作正常。

1 个答案:

答案 0 :(得分: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)

如果有更好的解决方案,请告诉我。请指导我这个approch哪个学期不好。谢谢。