[英]Django: Search Multiple Fields of A Django Model with Multiple Input field (with Drop Down) in HTML
How can I implement a Drop-Down search in Django where users can search through a listing of second hand cars. 如何在Django中实现下拉搜索,用户可以在其中搜索二手车列表。 The HTML search page will have 3 dropdown search input for Brand, Colour, Year. HTML搜索页面将有3个下拉菜单,分别是品牌,颜色,年份。 Once users select a choice of brand, colour and year, the listings will return a list of cars that matches that requirement. 一旦用户选择了品牌,颜色和年份,列表将返回符合该要求的汽车列表。
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)
I would appreciate any ideas on what I need to do. 对于任何需要做的想法,我将不胜感激。 I had a look at Q lookups, django haystack, but I'm unsure which would fit my needs. 我看过Q查询,django haystack,但是我不确定哪一个适合我的需求。 I think I would appreciate seeing how I could integrate this with the HTML side of things to pass the query from multiple input fields to Django. 我想我很高兴看到如何将其与事物的HTML方面集成在一起,以将查询从多个输入字段传递给Django。
You can do this with a new endpoint where you can search the cars based on the required filters. 您可以使用新的端点执行此操作,在该端点可以根据所需的过滤器搜索汽车。 I dont know if you want all of them combined to select cars or either one of which to be satisfied, because of which I have mentioned both. 我不知道您是否希望将它们全部组合在一起以选择汽车,或者其中之一要满足,因此我已经提到了两者。
Solution : 解决方案 :
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;
}
});
Ref : 参考 :
* AJAX Docs * AJAX文件
* How to make an AJAX request without jQuery * 如何在没有jQuery的情况下发出AJAX请求
* Q queries in Django * Django中的Q查询
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.