Reputation: 438
I am developing an app with Django framework and in a part of it I receive a class instance that contains data. Now I want to store this data in my database, what should I do?
For example if incoming is this:
>>>type(incoming)
<class 'foo.bar.model'>
>>>incoming.name
'hosein'
And the class attributes are: name, age, gender, phone_no ,...
Now I want to store all this attributes values in my app's model called app_name.models.Profile
I know that I can define a model like this:
models.py
class Profile(models.Model):
name = models.CharField(max_length = 255)
age = models.IntegerField()
# And so on ...
But this is not my answer, I'm searching for permanent and exact way except define and storing fields one by one. Is there any way to define some dynamic model fields for my model class?
Upvotes: 1
Views: 1270
Reputation: 25539
You could call each class method on incoming
objects to get results, then use the corresponding field name to store in a Profile
instance. Here's a rough example, you might need to tweak it a little to make it work for you:
# create a Profile object
new_profile = Profile()
for name in dir(incoming):
# loop on each method for incoming object
attribute = getattr(incoming, name)
if not ismethod(attribute):
# get the value of the attribute
value = attribute
setattr(new_profile, name, value)
new_profile.save()
python doc about getattr and setattr.
Upvotes: 2