开发者

In django, __init__ function on Model, causes attribute error, cannot save to database

I am using django and a model definition such as

class Question(models.Model):
    title = models.CharField(max_length=100)
    description = models.TextField()
    order = models.IntegerField()

    def __init__(self, *args, **kwargs):
        self.title = kwargs.get('title','Default Title')
        self.description = kwargs.get('description', 'DefDesc开发者_JAVA技巧ription')
        self.order = kwargs.get('order', 0)

Attempting to call save() on an object of the question class, causes the shell to respond with

/django/db/utils.py", line 133, in _route_db
    return hints['instance']._state.db or DEFAULT_DB_ALIAS
AttributeError: 'Question' object has no attribute '_state'

However, removing the _____init_____ function, makes everything ok again. Any idea on what causes this and how to resolve it?

many thanks


You need to call the superclass' __init__ method at some point in your subclass' __init__ method:

def __init__(self, *args, **kwargs):
    super(Question, self).__init__(*args, **kwargs)
    # your code here


According to the Django models docs, it's not recommended to overwrite __init__ method for models. Using @classmethod or custom manager is preferred.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜