Django:如何过滤形式

时间:2015-06-15 07:37:59

标签: django forms filter

我有一个模特

class Demande_Expertise(models.Model):
    user = models.ForeignKey(User)
    material = models.CharField(_('material'), max_length=30)
    categorie =  models.ForeignKey("Category")

class Category(models.Model):
    name = models.CharField(_('name'), max_length=50)

我有类别记录:合金,陶瓷,复合材料,铜基,金属,Pure_metals,Ni_based

形式

class Demande_ExpertiseForm(forms.ModelForm):
    class Meta:
        model = Demande_Expertise
        exclude =  ('etat',)

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

模板

<td>{{ form.categorie}}</td>

如果我想要模板,如何获取表格:陶瓷,铜基,镍基?

如果我写Demande_ExpertiseForm

self.fields['categorie'].queryset = Category.objects.filter(name__icontains="Cu_based")

我只获得了Cu_based的过滤器

如果我想要陶瓷,Cu基,Ni基过滤器 怎么办?

1 个答案:

答案 0 :(得分:0)

您可以使用'Q'

from django.db.models import Q

self.fields['categorie'].queryset = Category.objects.filter(Q(name__icontains = 'Cu_based') | Q(name_icontains = 'Ceramic') | Q(name_icontains = 'Ni_based'))