gpt4 book ai didi

javascript - 使用 ajax 和 django 根据用户提供的值进行过滤

转载 作者:太空宇宙 更新时间:2023-11-03 16:59:30 26 4
gpt4 key购买 nike

我正在尝试开发过滤系统。过滤系统提供特性类型、房间数量、最高价格等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?

要接受过滤器作为名为 roomsprice 的 GET 请求参数,我们可以看到如下所示的 View :

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
}
});

关于javascript - 使用 ajax 和 django 根据用户提供的值进行过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35113622/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com