I have to implement autocomplete search for my two different models "Destination and Regions", so I should send json response to my template according to query results consist of my two different querysets.
Do you think which View should I use in this case? Can anyone offer a best practice here ?
You could build a mixin for use in a ListView. You could piggyback on various ListView features like pagination / model / qs creation.
Not too different from just building a plain generic.base.View though!
from django.core import serializers
class AJAXListMixin(object):
     def dispatch(self, request, *args, **kwargs):
         if not request.is_ajax():
             raise http.Http404("This is an ajax view, friend.")
         return super(AJAXListMixin, self).dispatch(request, *args, **kwargs)
     def get_queryset(self):
         return (
            super(AJAXListMixin, self)
            .get_queryset()
            .filter(ajaxy_param=self.request.GET.get('some_ajaxy_param'))
         )
     def get(self, request, *args, **kwargs):
         return http.HttpResponse(serializers.serialize('json', self.get_queryset()))
class AjaxDestinationListView(AJAXListMixin, generic.ListView):
     # ...
You can probably see how to build this mixin in a model independent way, so that it can be reused across your Destinations and Regions model.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With