0

I have a model

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)

I have for the class Category the records : Alloys, Ceramic, Composite, Cu_based, Metals, Pure_metals, Ni_based

form

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

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

template

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

How do I get the form if I want to have for the template : Ceramic, Cu_based, Ni_based ?

if I write in Demande_ExpertiseForm

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

I get only the filter for Cu_based

if I want the filter for Ceramic, Cu_based, Ni_based how to do ?

Patrice
  • 209
  • 1
  • 4
  • 15

1 Answers1

0

You can use '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'))
hspandher
  • 15,934
  • 2
  • 32
  • 45
  • for the first : too many values tu unpack and for the second I have an empty dropdown – Patrice Jun 15 '15 at 11:26
  • Sorry my bad, I somehow thought it was an and operation. – hspandher Jun 15 '15 at 11:29
  • self.fields['categorie'].queryset = Category.objects.filter(reduce(lambda x, y: x | y, [Q(name__contains=word) for word in malist])) and with malist=['Cu_based', 'Ceramic', 'Ni_based', 'Ti_based']...... It works – Patrice Jun 15 '15 at 11:48