我在网上发现了很多关于此主题的类似帖子,但没有人明确指出哪个是问题。在Django中使用classmethod设置字段的默认值
代码
class Item(models.Model):
@classmethod
def get_next_item_number(cls):
return cls.objects.count() + 1
number = models.IntegerField(default=get_next_item_number)
问题
当我访问Django管理面板相关的 '数字' 域中的文本字段包含
<classmethod object at 0x7fab049d7c50>
所以我试图改变以上代码
class Item(models.Model):
@classmethod
def get_next_item_number(cls):
return cls.objects.count() + 1
number = models.IntegerField(default=get_next_item_number())
但是当我运行Django的服务器我得到:
number = models.IntegerField(default=get_next_item_number())
TypeError: 'classmethod' object is not callable
我知道这一切可以通过声明get_next_item_number()作为外部功能来防止,但是这种解决方案是不优雅我,因为get_next_item_number()是指只有Item类。
有没有我失踪的解决方案?您Item
类
看看:http://stackoverflow.com/questions/3786987/class-based-default-value-for-field-in-django-model-inheritance-hierarchy – xecgr 2014-09-02 12:07:40
这些解决方案不提供默认值时我构建了与Item模型关联的ModelForm。我宁愿使用外部函数。 – Sirion 2014-09-02 12:16:55