【发布时间】:2016-04-19 20:45:53
【问题描述】:
我想在现有模型中添加一个新字段,并将默认值作为模型中已存在的字段。
现有模型(仅举例)
class Product(models.Model)
name = models.CharField(max_length=127)
修改后的模型
class Product(models.Model):
name = models.CharField(max_length=127)
full_name = models.CharField(max_length=127)
我在这里添加新字段 full_name 并希望所有现有字段的值与 name 字段相同。
经过一些解决方案后,我知道我们可以定义和调用具有默认属性的方法,如下所示:
class Product(models.Model):
def get_name(self):
return self.name
name = models.CharField(max_length=127)
full_name = models.CharField(max_length=127, default=get_name)
但这会报错:
ValueError: Could not find function dt_default in cater.models.
Please note that due to Python 2 limitations, you cannot serialize unbound method functions (e.g. a method declared and used in the same class body). Please move the function into the main module body to use migrations.
For more information, see https://docs.djangoproject.com/en/1.8/topics/migrations/#serializing-values
然后我在类之外定义了这个方法,但是我无法访问self.name,因为那时我无权访问类实例。
任何人都可以请同样帮助我,将不胜感激。
【问题讨论】:
标签: python-2.7 django-models django-orm