Vor
Vor

Reputation: 35099

How to get values of all object fields in Django?

I'm trying to make a JSON that will look like this:

[
    {
        "num_of_followers": 2,
        "name": "Math 140",
        "created_by": "aaa"
    }
]

The problem is I don't really understand how I can get a list of values for one particular database object (another words how can I get the whole row )

@csrf_exempt
def create_subject(request, subject):
    subject, created= Subjects.objects.get_or_create( 
        name=subject,
        user=request.user,
        created_by=request.user)
    list = []
    columns = [Subjects._meta.get_all_field_names()]
    row = ????????
    for value in row:
        record = dict(zip(columns,value))
        list.append(record)
    result = simplejson.dumps(list, indent=4)
    return HttpResponse(result)

Upvotes: 18

Views: 36011

Answers (3)

Devin Gonier
Devin Gonier

Reputation: 11

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

Upvotes: 1

sekrett
sekrett

Reputation: 1275

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.

Upvotes: 18

Marat
Marat

Reputation: 15738

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

Upvotes: 12

Related Questions