我正在尝试开发过滤系统。筛选器系统提供3个选项,例如物业类型,房间数量和最高价格。根据这些选项中的选定值,用户将获得其搜索结果。例如,如果用户选择了公寓类型,房间数量为4,最高价格为12000,则用户将获得物业类型为带有42000个房间的公寓的房租。我使用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
和的GET请求参数price
,我们可以看到如下视图:
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
}
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句