Why can't I use __getattr__ with Django models?

≡放荡痞女 提交于 2019-12-05 02:52:16

One must be careful using __getattr__ . Only intercept what you know, and let the base class handle what you do not.

The first step is, can you use a property instead? If you want a "random" attribute which return 42 then this is much safer:

class Post(...):
  @property
  def random(self):
    return 42

If you want "random_*" (like "random_1", "random_34", etc) to do something then you'll have to use __getattr__ like this:

class Post(...):
  def __getattr__(self, name):
    if name.startswith("random_"):
      return name[7:]
    return super(Post, self).__getattr__(name)

Django sends certain signals when models are first initialized (ie, by loading up the shell) - by making it so that calls to __getattr always return an integer, you've modified the code in a way that Django signals weren't expecting (and therefore, they're breaking).

If you want to do this, maybe try it this way:

def __getattr__(self, attr):
  if hasattr(self, attr):
    return super(MyModel, self).__getattr__(attr)
  return 42
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!