-
-
Save gladson/3279899 to your computer and use it in GitHub Desktop.
Serializar detalhamento ou listagem de dados customizados em json com CBV
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# API JSON | |
from django.http import HttpResponse | |
from django.utils import simplejson | |
from django.views.generic.detail import BaseDetailView | |
from django.views.generic.list import BaseListView | |
from django.db.models.query import QuerySet | |
class JSONResponseMixin(object): | |
def render_to_response(self, context): | |
return self.get_json_response(self.convert_context_to_json(context)) | |
def get_json_response(self, content, **httpresponse_kwargs): | |
return HttpResponse(content, content_type='application/json', **httpresponse_kwargs) | |
def convert_context_to_json(self, context): | |
return simplejson.dumps(context) | |
class JSONDetailView(JSONResponseMixin, BaseDetailView): | |
def render_to_response(self, context): | |
obj = context['object'].as_dict() | |
return JSONResponseMixin.render_to_response(self, obj) | |
class JSONListView(JSONResponseMixin, BaseListView): | |
def render_to_response(self, context): | |
obj_list = list(self.model.objects.values()) | |
return JSONResponseMixin.render_to_response(self, obj_list) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.db import models | |
class Estado(models.Model): | |
sigla = models.CharField(max_length=2) | |
class Meta: | |
ordering = ['sigla'] | |
@property | |
def cidades(self): | |
cidades = self.cidade_set.all() | |
clist = [] | |
for cidade in cidades: | |
clist.append( | |
{'pk': cidade.pk, 'nome': cidade.nome} | |
) | |
return clist | |
def __unicode__(self): | |
return self.sigla | |
def as_dict(self): | |
return { | |
'pk': self.pk, | |
'sigla': self.sigla, | |
'cidades': list(self.cidades), | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# coding=utf-8 | |
from django.conf.urls import patterns, url | |
from address.models import Estado | |
from core.api.json_response import JSONDetailView, JSONListView | |
urlpatterns = patterns('', | |
url(r'^estado/(?P<pk>\d)$', JSONDetailView.as_view(model=Estado), name="estado"), | |
url(r'^estados/$', JSONListView.as_view(model=Estado), name="estados"), | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment