Best way to create a model search form?

I have this model:

class Aircraft(models.Model):
    model       =   models.CharField(max_length=64, blank=True)
    type        =   models.CharField(max_length=32)
    extra       =   models.CharField(max_length=32, blank=True)
    manufacturer    =   models.CharField(max_length=32)
    engine_type =   models.IntegerField("Engine Type", choices=ENGINE_TYPE, default=0)
    cat_class   =   models.IntegerField("Category/Class", choices=CAT_CLASSES, default=1)

And I have a page “find an airplane”, where the user is presented with a form in which they can enter data that will be used to find all planes that match their criteria. For example, a user may enter “boeing” in a text field and “jet” in a field engine_type, and he will display all Boeing combat aircraft in the database. Now I do this in this form:

class AircraftSearch(ModelForm):
    search = forms.CharField(max_length=100, required=False)
    class Meta:
        model = Aircraft
        fields = ('engine_type', 'cat_class', )

And then a (unnecessarily complex) view that converts the data from this form into a set filter()that is added to Aircraft.objects.all(). (Instead of having 4 separate search fields for each CharField, I combined them all into one search field.)

, . , , "" . / /, "Any",

. ? , - , google .

+5
2

"" , .

, ModelForm ; , , :

class AircraftSearch(forms.Form):
    search = forms.CharField(max_length=100, required=False)
    engine_type = forms.ChoiceField(choices=ENGINE_TYPE)
    cat_class = forms.ChoiceField(choices=CAT_CLASS)

, , :

def search(request):
    if request.method == 'POST':
        results = Aircraft.objects.all()

        search = request.POST.get('search', None)
        if search:
            results = results.filter(Q(model=search)|Q(type=search)|Q(extra=search)|Q(manufacturer=search))

        engine_type = request.POST.get('engine_type', None)
        if engine_type:
            results = results.filter(engine_type=engine_type)

        cat_class = request.POST.get('cat_class', None)
        if cat_class:
            results = results.filter(cat_class=cat_class)

        return render_to_response('aircraft.html', {'form': AircraftSearch(request.POST), 'aircraft': results})

    return render_to_response('aircraft.html', {'form': AircraftSearch()})
+8

, ModelForm.
ModelForm , .

, , , (), .
, , , .

+3

All Articles