代码: 模型
class A1(models.Model):
user = models.ForeignKey(User)
field1 = models.CharField(max_length=200)
field2 = models.CharField(max_length=200)
class A2(models.Model):
user = models.ForeignKey(User)
field1 = models.CharField(max_length=200)
field2 = models.CharField(max_length=200)
field3 = models.CharField(max_length=200)
用法:
def insertRecord(modelName, fields, user)
record = modelName(User=user, **fields)
record.save()
错误:' unicode'对象不可调用。
输入: modelName:A2 字段:{u' field1&#39 ;: u' d2d2d2',u' field2':u' e2e2e2',u' field3':u&# 39; f2f2f2'}类型(字段):' dict'
任何解决方案/解决这个问题吗? 谢谢,
答案 0 :(得分:1)
您必须设置属性:
def insertRecord(modelName, fields, user)
if modelName == "A1":
record = A1(User=user)
else:
record = A2(User=user)
for field, value in fields.iteritems():
setattr(record, field, value)
或简单地说:
def insert_record(model_name, fields, user):
cls = A1 if model_name == 'A1' else A2
return cls(User=user, **fields)