English 中文(简体)
在另存方法内使用模型类的方法
原标题:Use method of model class within save method

我试图推翻我的一个模型的保存方法。在这个保存方法中,我想使用另一种模式方法,例如:

class MyModel(models.Model):
    name = models.CharField(max_length=255)

    def do_something(self):
        pass

    def save(self,*args, **kwargs):
        self.do_something()
        super(MyModel, self).save(*args, **kwargs)

这不起作用, 因为当 Django 执行保存时, 对象是一个通用的 ModelBase 类, 而不是我的 ModeBase 子类 。 因此我理解 :

unbound method do_something() must be called with MyModel instance as first argument (got ModelBase instance instead)

这样做的正确方式是什么?

问题回答

您应该将 args kwargs 置于被覆盖的 save () 方法上 :

class MyModel(models.Model):
    name = models.CharField(max_length=255)

    def do_something(self):
        pass

    def save(self, *args, **kwargs):
        self.do_something()
        super(MyModel, self).save(*args, **kwargs)

您也忘记了 self 参数在 do_ something () !

<强> UPDATE

我不太理解你的问题。 如果您想要调用无约束方法 do_ something , 请在类外 MyModel 定义一个, 只需从 save () 中调用它, 如“ do_ something( self) ” :

class MyModel(class.Model):
  def save(self, *args, **kwargs):
    do_something(self)
    super(MyModel, self).save(*args, **kwargs)

def do_someting(my_model_instance):
  assert isinstance(my_model_instance, MyModel)
  ...




相关问题
How to get two random records with Django

How do I get two distinct random records using Django? I ve seen questions about how to get one but I need to get two random records and they must differ.

Moving (very old) Zope/Plone Site to Django

I am ask to move data from a (now offline) site driven by Plone to a new Django site. These are the version informations I have: Zope Version (unreleased version, python 2.1.3 ) Python Version 2.1....

Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

Flexible pagination in Django

I d like to implement pagination such that I can allow the user to choose the number of records per page such as 10, 25, 50 etc. How should I go about this? Is there an app I can add onto my project ...

is it convenient to urlencode all next parameters? - django

While writing code, it is pretty common to request a page with an appended "next" query string argument. For instance, in the following template code next points back to the page the user is on: &...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

热门标签