我正在尝试开发过滤系统。过滤系统提供3个选项,如房产类型,房间数量和最高价格。根据这些选项中的选定值,用户将获得他们的搜索结果。例如,如果用户选择了公寓的房产类型和房间数为4,最高价格为12000,则用户将获得其房产类型为公寓的租金,其中4个房间为12000标记。我使用React.js开发了前端部分,可以成功获取用户选择的数据。我也将数据传递给ajax但我不知道我应该在服务器端做什么(Django Views)。有人可以赐教我吗?我是在正确的轨道上吗?
我的ajax代码:
$.ajax({
type:'GET',
url:'/filter/space/',
data:{property:propertySelectedValue,room:roomSelectedValue,price:maxPrice},
success:function(data){
},
error:function(XMLHttpRequest, textStatus, errorThrown){
console.error("Status: " + textStatus); alert("Error: " + errorThrown);
},
});
},
Views.py
class FilterSpace(View):
def get(self,request,*args,**kwargs):
property = request.GET.get('property',None)
room = request.GET.get('room', None)
price = request.GET.get('price', None)
rental = Rental.objects.all()
if room:
rental = rental.filter(room=room)
print(rental)
if price:
rental = rental.filter(price__lte=price)
if property:
rental = rental.filter(property=property)
rental_json = serializers.serialize('json',rental)
return HttpResponse(rental_json),content_type="application/json")
答案 0 :(得分:1)
让我们假设一个像这样的Django模型:
class Apartment(models.Model):
rooms = models.IntegerField()
price = models.IntegerField() # Can use Decimal,
# but who quotes real estate prices with decimals?
要接受名为rooms
和price
的GET请求参数的过滤器,我们可以进行如下视图:
from django.views.generic import View
class ApartmentSearch(View):
def get(self, request):
rooms = request.GET.get('rooms', None)
price = request.GET.get('price', None)
# The base query takes all apartments
apartments = Apartment.objects.all()
# If a filter param is passed, we use it to filter
if rooms:
apartments = apartments.filter(rooms=rooms)
if price:
apartments = apartments.filter(price__lte=price)
# Here you need to convert to JSON
apartments_json = <convert to JSON>
return HttpResponse(apartments_json)
要从jQuery发送参数,请执行以下操作:
$.ajax({
url: "/api/apartment/search",
type: "get", // HTTP GET
data: {property: ..., rooms: ..., price: ...}, // The filter object
success: function(response) {
//Do Something
},
error: function(xhr) {
//Do Something to handle error
}
});