Django. Get values for all fields in one object Django. Get values for all fields in one object django django

Django. Get values for all fields in one object


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

from django.forms.models import model_to_dictvalues = model_to_dict(the_object)

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


use .values() queryset method:

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


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