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)
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.
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
)
)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With