Django:在HTML中搜索具有多个输入字段(带下拉菜单)的Django模型的多个字段

时间:2018-11-23 07:20:50

标签: python html django

如何在Django中实现下拉搜索,用户可以在其中搜索二手车列表。 HTML搜索页面将有3个下拉菜单,分别是品牌,颜色,年份。一旦用户选择了品牌,颜色和年份选择,列表就会返回符合该要求的汽车列表。

class SecondHandCar(models.Model):
    brand = models.CharField(max_length=250, unique=True)
    slug = models.SlugField(max_length=250, unique=True)
    description = models.TextField(blank=True)
    colour = models.CharField(Category, on_delete=models.CASCADE)
    year = models.IntegerField(blank=False)

对于我需要做的任何想法,我将不胜感激。我看过Q查询,django haystack,但是我不确定哪一个适合我的需求。我想我很高兴看到如何将其与事物的HTML方面进行集成,以将查询从多个输入字段传递给Django。

1 个答案:

答案 0 :(得分:1)

您可以使用新的端点来执行此操作,您可以在该端点上根据所需过滤器搜索汽车。我不知道您是否希望将它们全部组合在一起以选择汽车,或者其中之一要满足,因此我已经提到了两者。

解决方案

url(r'^search_cars/$'. views.search_cars, name='search-cars')

def search_cars(request, *args, **kwargs):
    content_type = 'application/json'

    # I think you only need ajax, but you can choose to remove this
    if request.is_ajax():
        brand = request.GET.get('brand')
        colour = request.GET.get('colour')
        year = request.GET.get('year')

        # checking if all 3 are present
        if brand is None or color is None or year is None:
            return HttpResponse({
                'success': False,
                'message': 'Required fields are missing.'
            }, content_type=content_type)

        # depending on how you want to filter
        # this will choose cars which have either brand, colour or year
        filters = Q(Q(brand=brand) | Q(color=colour) | Q(year=year))
        second_hand_cars = SecondHandCars.objects.filter(filters)

        # or
        # you can choose cars which satisfy all three of these together
        filters = {'brand': brand, 'colour': colour, 'year': year}
        second_hand_cars = SecondHandCars.objects.filter(**filters)

        # serialize the objects and return the json response
        data = []
        for car in second_hand_cars:
            data.append({
                'brand': car.brand,
                'colour': car.colour,
                'year': car.year,
                'description': car.description,
                'slug': car.slug
            })

        return HttpResponse({
            'success': True,
            'data': data,
        }, content_type=content_type)
    else:
        return HttpResponse({
            'success': False,
            'message': 'Only AJAX method is allowed.'
        }, content_type=content_type)

// JavaScript code to make an ajax request
// when all three dropdowns are selected with appropriate values.
// assuming you are using jQuery.

// add a common class to all 3 dropdowns to monitor changes
$(document).on('change', '.filter-dropdown', function() {
    # all three will provide attribute `value` of `option` tag.
    var brand = $('#brandDropdown').children('option:selected').val();
    var colour = $('#colourDropdown').children('option:selected').val();
    var year = $('#yearDropdown').children('option:selected').val();

    # add a default selected `option` tag with value `""`
    if (brand !== "" && colour !== "" && year !== "") {
        var data = {
            'brand': brand,
            'colour': colour,
            'year': year
        }

        $.ajax({
            url: '/search_cars/',
            type: 'GET',
            data: data,
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    // render cars from `response.data`
                } else {
                    // show message from `response.message`
                }
            },
            error: function(errorResponse) {
                // show error message
            }
        });
    } else {
        return;
    }
});

参考
 * AJAX Docs
 * How to make an AJAX request without jQuery
 * Q queries in Django