Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django. Get values for all fields in one object

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)
like image 453
Vor Avatar asked Sep 10 '12 23:09

Vor


3 Answers

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.

like image 200
sekrett Avatar answered Oct 24 '22 03:10

sekrett


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
        )
    )
like image 11
Marat Avatar answered Oct 24 '22 05:10

Marat


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
like image 1
Devin Gonier Avatar answered Oct 24 '22 04:10

Devin Gonier