I am trying to design an api for search functionality. I want an API for implementing in the reactjs. What i want is /api/v1/rent/search/place="place name" but i am not getting this. What i did was
api.py
from rentals.models import Rental,Gallery
from django.core.paginator import InvalidPage
from django.conf.urls import *
from tastypie.paginator import Paginator
from tastypie.exceptions import BadRequest
from tastypie.resources import ModelResource
from tastypie.utils import trailing_slash
from haystack.query import SearchQuerySet
class SearchResource(ModelResource):
class Meta:
queryset = Rental.objects.all()
resource_name = 'rent'
def prepend_urls(self):
return [
url(r"^(?P<resource_name>%s)/search%s$" % (
self._meta.resource_name,
trailing_slash()),
self.wrap_view('get_search'),
name="api_get_search"
),
]
def get_search(self, request, **kwargs):
self.method_check(request, allowed=['get'])
self.is_authenticated(request)
self.throttle_check(request)
# Do the query.
sqs = SearchQuerySet().models(Rental).load_all().auto_query(request.GET.get('q', ''))
paginator = Paginator(sqs, 20)
try:
page = paginator.page(int(request.GET.get('page', 1)))
except InvalidPage:
raise Http404("Sorry, no results on that page.")
objects = []
for result in page.object_list:
bundle = self.build_bundle(obj=result.object, request=request)
bundle = self.full_dehydrate(bundle)
objects.append(bundle)
object_list = {
'objects': objects,
}
self.log_throttled_access(request)
return self.create_response(request, object_list)
models.py
class Rental(models.Model):
city = models.CharField(_("City"), max_length=255, blank=False,null=True,
help_text=_("City of the rental space"))
place = models.CharField(_("Place"), max_length=255, blank=False,null=True,
help_text=_("Place of the rental space"))
class Gallery(models.Model):
rental = models.ForeignKey('Rental', null=True, on_delete=models.CASCADE,verbose_name=_('Rental'), related_name="gallery")
image = models.ImageField(blank=True,upload_to='upload/',null=True)
What else do i have to do to achieve the url like api/v1/rent/search/place="place name"(i want to search from the place name) ?
Add this to the top of your Python file:
from django.core.paginator import InvalidPage