首页 > 解决方案 > 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
def generate_token(self, apply=True, length=5):
    ...

self.code = SaleCode.generate_token()["token"] #the line that generates the error

标签: pythondjangodjango-models

解决方案


我真的不知道为什么,但是...

我刚刚重新启动了服务器,它工作了.. 真的很奇怪,但知道它可以工作。


推荐阅读