python - Django 在同一模型的另一个方法中调用模型方法(在 models.py 中)?
问题描述
只需重新启动服务器即可解决 ( python manage.py runserver
)
我想在models.py中的另一个模型方法中调用模型方法,但我收到错误AttributeError: module 'my_website.models' has no attribute 'my_model_method'
这是我的模型:
class SaleCode(models.Model):
#my fields and methods...
#the method I want to call
def generate_token(self, apply=True, length=5):
# stuff
return {
"token": token,
"self-applyed": apply
}
#save() method override
def save(self, *args, **kwargs):
if not self.pk:
#self.code is one of my fields
self.code = self.generate_token()["token"] #the line that generates the error
super(SaleCode, self).save(*args, **kwargs)
我试过的:
- (当我在某处读到时)我试图将
@classmethod
(和@staticmethod
)放在generate_token(...)
声明上,然后将其称为SaleCode.generate_token()
:
@classmethod
def generate_token(self, apply=True, length=5):
...
self.code = SaleCode.generate_token()["token"] #the line that generates the error
- 我在方法之外编写了函数,然后将其作为普通函数调用(它有效,但似乎不是一种“明确”的方法。)
解决方案
我真的不知道为什么,但是...
我刚刚重新启动了服务器,它工作了.. 真的很奇怪,但知道它可以工作。
推荐阅读
- java - Java 8 ZonedDateTime 格式日期
- pywin32 - 有人知道如何在虚拟环境中使用 pywin32 吗?
- php - PHP dom解析器:只有在另一个元素之后才获取元素计数?
- r - 在同一数据框中总结多个组的更好方法
- python - python strftime不带前导0
- google-sheets - 在表格脚本中暂停一下,睡眠不起作用
- protocol-buffers - 如何为 Protocol Buffers rpc 方法定义空参数?
- java - Pig it method that I am trying to make trouble checking punctuation at the end java
- git - new PR includes changes from older PR in Github
- google-api - YouTube API is adding 101 uses for each request instead of one