[Fixed]-How to return table data as different format types via views in Django

1👍

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))

Leave a comment