jcage
jcage

Reputation: 651

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', 'DefDescription')
        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

Upvotes: 6

Views: 3313

Answers (2)

arsenyinfo
arsenyinfo

Reputation: 428

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

Upvotes: 2

Joseph Spiros
Joseph Spiros

Reputation: 1304

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

Upvotes: 11

Related Questions