Search code examples
pythondjangodictionarymodelrepresentation

String Dictionary Representation of a Model/Object instance in Python/Django?


I feel that this is a very simple question, but I'm new to Python, and I'm learning Django at the same time.

My objective is to create a string dictionary representation i.e. it's dictionary formatted but a string, of a Model's instance in Django. How could I do that? Is there a built-in function that I can call straight from the object's instance, or do I have to define one?

UPDATE:

I would like to call this functionality within the model definition itself i.e. I'm implementing a class method or function which needs this functionality. I'm thinking of a functionality which behaves like python's built-in function locals() but should only return the model's attributes.

I also would like to add that I'll be calling this functionality on a model's instance which has not been saved yet to the database. So in essence, I'll be working on a model's instance representing a record which is not yet in the database. So anything function using a Manager or QuerySet I guess is not why I'm looking for.

Example:

class Person(models.Model):
     name = ...
     age =  ...

     def func_doing_something(self):
          #get the string dictionary representation of this model's instance
          #do something to it
          #return something

Thanks everyone!


Solution

  • I found from this SO post the solution I was looking for...

    some Django object obj

    [(field.name, getattr(obj,field.name)) for field in obj._meta.fields]
    

    and just call dict() on the result.