Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use django class based views for sending json consist of different model querysets

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 ?

like image 552
tuna Avatar asked Dec 11 '22 15:12

tuna


1 Answers

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.

like image 159
Yuji 'Tomita' Tomita Avatar answered Dec 22 '22 16:12

Yuji 'Tomita' Tomita