我正在尝试使用django创建一个字符串对象
我的模特:
lines = []
with open('file.txt', 'r+') as f:
# You can actually process the file line by line without saving it into a list:
for line in f:
# For clearer code, you can index the split function here:
line = line.split(' ', 1)[0]
lines.append(line)
创建代码:
class Example(models.Model):
user_id = models.IntegerField(blank=True, null=True)
field_1 = models.DecimalField(max_digits=15, decimal_places=2, blank=True, null=True)
field_2 = models.DecimalField(max_digits=15, decimal_places=2, blank=True, null=True)
field_3 = models.DecimalField(max_digits=15, decimal_places=2, blank=True, null=True)
如何创建此。..谢谢.. !!
答案 0 :(得分:0)
real_field = "field_"+str(level)
example = Example(
user_id=user_id,
......
)
example.setattr(real_field,value_1)
example.save()
setattr是您要寻找的东西
或
data = {}
data["field_"+str(level)] = value1
example = Example(
user_id=user_id,
......,
**data
)
example.save()
答案 1 :(得分:0)
您可以将字典传递给模型构造函数:
example = Example(**{
'user_id': user_id,
real_field: value_1,
......
})
example.save()