使用queryset过滤django M2M字段选项

时间:2014-10-30 08:33:02

标签: django django-queryset manytomanyfield

我想使用查询集过滤表单的M2M字段中显示的选项。我已经读过limit_choices_to只能与ForeignKey一起使用。是否有类似limit_choices_to的内容可以应用于M2M?

这是我的模特:

class Inspection(models.Model):

    ref         = models.CharField(max_length=50)
    tools       = models.CharField(max_length=150,null=True,blank=True)
    areas       = models.ManyToManyField('specimens.Area',null=True,blank=True)

这是M2M领域的典范:

class Area(models.Model):

    ref         = models.CharField(max_length=10)
    description = models.TextField(max_length=150)
    specimen    = models.ForeignKey(Specimen)

    class Meta:
        unique_together = ['ref','specimen']

我想用queryset过滤inspection_areas: Area.objects.filter(specimen="specimen")

其他帖子(Many to many and how to get a queryset from queryset)解释了这样做的方法,更改了我认为的管理员表单(我不太了解它),但这对我不起作用,获得DoesNotExist错误或Super错误。我是否必须更改InspectionForm之前发布帖子的InspectionAdminForm

enter image description here

有什么想法吗?

EDIT-1:

我意识到它会抛出其他不同的错误:

enter image description here

这是我用过的完整代码:

class InspectionAdminForm(forms.ModelForm):

    class Meta:
        model = Inspection

    def __init__(self, *args, **kwargs):
        super(InspectionAdminForm,self).__init__(*args,**kwargs)
        self.fields['areas'].queryset = Area.objects.filter(specimen=self.instance.specimen)



class InspectionAdmin(admin.ModelAdmin):
    form = InspectionAdminForm
    filter_horizontal = ['areas']

1 个答案:

答案 0 :(得分:0)

正如我为Inspection modelForm设置了一些初始参数,我设置了:

inspectionform = InspectionForm(None, initial={'specimen':specimen})

我还更改了InspectionForm的__init__方法:

class InspectionForm(forms.ModelForm):

    class Meta:
        model = Inspection

    def __init__(self, *args, **kwargs):
        super(InspectionForm,self).__init__(*args,**kwargs)
        self.fields['areas'].queryset = Area.objects.filter(specimen=kwargs['initial']['specimen'].id)

这就是全部!现在它很棒。