Django. Get values for all fields in one object

use .values() queryset method:

@csrf_exempt
def create_subject(request, subject):
    subject, created= Subjects.objects.get_or_create( 
        name=subject,
        user=request.user,
        created_by=request.user)

    return HttpResponse(
        simplejson.dumps(
            list(models.Subject.objects.filter(id=subject.id).values()), 
            indent=4
        )
    )

If you are asking how to do that for ONE object, then you should use:

from django.forms.models import model_to_dict


values = model_to_dict(the_object)

@Marat answer is nice and it works but it is for a QuerySet, not one object.


I struggled a bit with getting the file field to work properly. In the end this is what worked for me.

def queryset_object_values(object):
    fields = [field.name for field in list(type(object)._meta.fields)]
    field_values = [(field, getattr(object, field)) for field in fields]
    out = {}
    for field in field_values:
        if isinstance(field[1], FieldFile):
            out[field[0]] = field[1].url
        else:
            out[field[0]] = field[1]
    return out