Django Model to Associative Array
<p>Is there any way to convert a django models to an associative array using a loop for HttpResponse.</p>

<pre><code>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)
</code></pre>

<p>my expected result was like this</p>

<pre><code>{ 
    "fname" : "sample",
    "mname" : "sample",
    "lname" : "sample",
    ...
}
</code></pre>

<pre><code>SomeModel.objects.filter(id=pk).values()[0]
</code></pre>

<p>You will get</p>

<pre><code>{ 
    "fname" : "sample",
    "mname" : "sample",
    "lname" : "sample",
    ...
}
</code></pre>

<p>I discourage the using of <code>__dict__</code> because you will get extra fields that you don't care about.</p>

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

<pre><code>class Guest(models.Model):
     #fields....


    def get_dict(self):
        return { 
            "fname" : self.fname,
            "mname" : self.mname,
            "lname" : self.lname,
        }
</code></pre>

<p>use it as it: <code>instance.get_dict()</code></p>

python django