0

Is there any way to convert a django models to an associative array using a loop for HttpResponse.

class Guest(models.Model):
    fname = models.CharField(max_length=200)
    mname = models.CharField(max_length=200, default="", blank=True, null=True)
    lname = models.CharField(max_length=200)
    gender = models.CharField(max_length=20, choices=gender_choices, default="")
    birth_date = models.DateField()
    address = models.TextField()
    phone = models.CharField(max_length=20)
    mobile = models.CharField(max_length=20, default="", blank=True, null=True)
    fax = models.CharField(max_length=20, default="", blank=True, null=True)
    email = models.CharField(max_length=200)
    id_type = models.CharField(max_length=200, default="", blank=True, null=True)
    id_number = models.CharField(max_length=200, default="", blank=True, null=True)

my expected result was like this

{ 
    "fname" : "sample",
    "mname" : "sample",
    "lname" : "sample",
    ...
}
KrLontoc
  • 117
  • 9
  • See http://stackoverflow.com/questions/21925671/convert-django-model-object-to-dict-with-all-of-the-fields-intact, though it sounds like you are in need for "django rest framework" which was made for this task (see its serializers) – serg Sep 14 '16 at 03:31

2 Answers2

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
  • 22,001
  • 7
  • 73
  • 74
  • i've tried the " Guest.objects.get(id=pk).values() " but and exception " 'Guest' object has no attribute 'values' " was returned. – KrLontoc Sep 14 '16 at 06:06
  • 1
    @KrLontoc Sorry, I updated my answer, its `SomeModel.objects.filter(id=instance.id).values()[0]` – levi Sep 14 '16 at 06:08
0
guest = Guest.objects.get(pk=1)
print guest.__dict__
Andrey Shipilov
  • 1,986
  • 12
  • 14