我正在使用 Django 框架开发一个应用程序,在其中的一部分中,我收到一个包含数据的类实例。现在我想将这些数据存储在我的数据库中,我应该做什么?
例如,如果传入是这样的:
>>>type(incoming)
<class 'foo.bar.model'>
>>>incoming.name
'hosein'
类属性为:姓名、年龄、性别、电话号码、...
现在我想将所有这些属性值存储在我的应用程序模型中,名为app_name.models.Profile
我知道我可以定义这样的模型:
models.py
class Profile(models.Model):
name = models.CharField(max_length = 255)
age = models.IntegerField()
# And so on ...
但这不是我的答案,我正在寻找除了一一定义和存储字段之外的永久且准确的方法。 有没有办法为我的模型类定义一些动态模型字段?
最佳答案
您可以在传入
对象上调用每个类方法来获取结果,然后使用相应的字段名称存储在Profile
实例中。这是一个粗略的示例,您可能需要对其进行一些调整才能使其适合您:
# 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 - 在 django 模型中存储类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36578950/