我正在尝试开发过滤系统。筛选器系统提供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")
最佳答案
让我们假设这样的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
}
});