[Answered ]-Filter based on user provided values with ajax and django

2👍

Let’s assume a Django model like this:

class Apartment(models.Model):
    rooms = models.IntegerField()
    price = models.IntegerField() # Can use Decimal,
                                  # but who quotes real estate prices with decimals?

To accept filters as GET request params called rooms and price, we can a view like below:

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)

To send the parameters from jQuery I’d do:

$.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
  }
});
👤bakkal

Leave a comment