Skip to main content
deleted 12 characters in body
Source Link
MD. Khairul Basar
  • 5.1k
  • 15
  • 43
  • 65

Lots of interesting solutions here. My solution was to add an as_dict method to my model with a dict comprehension.

 def as_dict(self):   return dict((f.name, getattr(self, f.name)) for f in self._meta.fields) 

As a bonus, this solution paired with an list comprehension over a query makes for a nice solution if you want export your models to another library. For example, dumping your models into a pandas dataframe:

 pandas_awesomeness = pd.DataFrame([m.as_dict() for m in SomeModel.objects.all()]) 

Lots of interesting solutions here. My solution was to add an as_dict method to my model with a dict comprehension.

 def as_dict(self):   return dict((f.name, getattr(self, f.name)) for f in self._meta.fields) 

As a bonus, this solution paired with an list comprehension over a query makes for a nice solution if you want export your models to another library. For example, dumping your models into a pandas dataframe:

 pandas_awesomeness = pd.DataFrame([m.as_dict() for m in SomeModel.objects.all()]) 

Lots of interesting solutions here. My solution was to add an as_dict method to my model with a dict comprehension.

def as_dict(self): return dict((f.name, getattr(self, f.name)) for f in self._meta.fields) 

As a bonus, this solution paired with an list comprehension over a query makes for a nice solution if you want export your models to another library. For example, dumping your models into a pandas dataframe:

pandas_awesomeness = pd.DataFrame([m.as_dict() for m in SomeModel.objects.all()]) 
Source Link
t1m0
  • 735
  • 1
  • 7
  • 14

Lots of interesting solutions here. My solution was to add an as_dict method to my model with a dict comprehension.

 def as_dict(self): return dict((f.name, getattr(self, f.name)) for f in self._meta.fields) 

As a bonus, this solution paired with an list comprehension over a query makes for a nice solution if you want export your models to another library. For example, dumping your models into a pandas dataframe:

 pandas_awesomeness = pd.DataFrame([m.as_dict() for m in SomeModel.objects.all()])