Satheesh Panduga
Satheesh Panduga

Reputation: 818

How to return table data as different format types via views in Django

I have below view which returns data of three different models Employees,Testimonial and Skills and it is perfectly working.

Views.py

@page_template("app/profession.html") # just add this decorator
def profile(request, template="app/profession.html",
extra_context=None):
context = {
    'employ_V': Employees.objects.get(id = 45),
    'testim_V':Testimonial.objects.get(id = 45),
    'skills_V':Skills.objects.filter(id = 45),
}
if extra_context is not None:
    context.update(extra_context)
return render_to_response(template, context,
    context_instance=RequestContext(request))

If you see, there is only one record that will be returned for Employees and Testimonial models (Notice objects.get() in the query) whereas Skills model has more than 1 record (it returns id,skill,order fields for more than 5 rows).

Is it possible to use same view to return Skills as Json format along with Employee and Testimonial to my template (plain text and JSON) ? Or should I use separate view to return data in Json format for Skills model ? What could be the best approach in this case.

In a separate view for Skills - I could achieve the results successfully in JSON format - for this I used customer serializer and JsonResponse.

Upvotes: 0

Views: 256

Answers (1)

madzohan
madzohan

Reputation: 11808

You can use Django values from queryset, but if you need special transformation (like thumbnail for image or so on) add to your model as_dict method

class YourModel(models.Model):
    # here your fields

    def as_dict(self):
        context = {
            'pk': self.id,
            'name': self.name,
            # ...
        }

        return context

Then in your views

# import section 
from django.utils.safestring import mark_safe
# ...


@page_template("app/profession.html") # just add this decorator
def profile(request, template="app/profession.html", extra_context=None):

    employ_v_obj = Employees.objects.get(id=45)
    testim_v_obj = Testimonial.objects.get(id=45)
    skills_v_qs = Skills.objects.filter(id=45)

    skills_v_json_list = [obj.as_dict() for obj in skills_v_qs]

    context = {
        'employ_V': employ_v_obj,
        'testim_V': testim_v_obj,
    }

    context['skills_V_json'] = mark_safe(json.dumps(skills_v_json_list, ensure_ascii=False))

    if extra_context is not None:
        context.update(extra_context)

    return render_to_response(template, context, context_instance=RequestContext(request))

Upvotes: 1

Related Questions