[Fixed]-Django Model to Associative Array

1👍

SomeModel.objects.filter(id=pk).values()[0]

You will get

{ 
    "fname" : "sample",
    "mname" : "sample",
    "lname" : "sample",
    ...
}

I discourage the using of __dict__ because you will get extra fields that you don’t care about.

Or you can create to_dict method in your models if you want to something more customisable in order to add calculated fields.

class Guest(models.Model):
     #fields....


    def get_dict(self):
        return { 
            "fname" : self.fname,
            "mname" : self.mname,
            "lname" : self.lname,
        }

use it as it: instance.get_dict()

👤levi

0👍

guest = Guest.objects.get(pk=1)
print guest.__dict__

Leave a comment