Django表单对象过滤器

时间:2014-01-21 09:15:40

标签: django django-forms django-queryset

我想关联下拉列表材料和类别

模型

class Demande_Expertise(models.Model):
    user = models.ForeignKey(User)
    material = models.ForeignKey("Material")
    categorie =  models.ForeignKey("Category")     

class Category(models.Model):
    name = models.CharField(_('name'), max_length=50)
    slug = models.SlugField()
    expert = models.ForeignKey(Expert, null=True, blank=True, default = None)

class Material(models.Model):
    name = models.CharField(_('name'), max_length=50)
    description = models.TextField(_('description'), blank=True)
    slug = models.SlugField()
    category = models.ForeignKey(Category, verbose_name=_('category'))

形式

class Demande_ExpertiseForm(forms.ModelForm):
    class Meta:
    model = Demande_Expertise

def __init__(self, *args, **kwargs):
    super(Demande_ExpertiseForm, self).__init__(*args, **kwargs)
    self.fields['material'].queryset = Material.objects.filter(category=Category)

没有错误,但过滤不起作用。

如何过滤模型name的{​​{1}}?

1 个答案:

答案 0 :(得分:0)

您可以使用双下划线(在这种情况下为category__name)过滤字段在查询集中的关系,并传入您想要过滤的任何内容。

class Demande_ExpertiseForm(forms.ModelForm):
    class Meta:
        model = Demande_Expertise

    def __init__(self, *args, **kwargs):
        super(Demande_ExpertiseForm, self).__init__(*args, **kwargs)

        self.fields['material'].queryset = Material.objects.filter(category__name="name to filter")

在这种情况下,它会将所有Material个对象过滤为Category设置为name to filter的对象。您可以阅读the Django documentation on retrieving objects了解更多信息。