In django, the __init__ function on the model causes an attribute error, cannot save to the database

I am using django and model definition like

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 a question class object causes the shell to respond

/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, deleting the _____init_____ function does everything right again. Any idea what causes this and how to solve it?

many thanks

+5
source share
2 answers

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

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

According to the Django docs , it is not recommended to overwrite a method __init__for models. A recommended @classmethodor custom manager is recommended .

+2

All Articles