You shouldn't really try and to this in the __init__
. (In fact, it's best to leave the __init__
of Django models well alone.) It should go in the form, or the view.
In any case, you can't overwrite an instance inside itself by assigning to self
- that's just a local variable like any other and will go out of scope at the end of the method.
Also note that you can use the defaults
parameter to get_or_create
to pass default values to be set on the new instance if an existing one is not found:
question, created = Question.objects.get_or_create(text=text, defaults={'asked': True})
Edit after question update Your edit makes it even clearer that __init__
is really not the place to be doing this. Don't forget, even evaluating a normal queryset will instantiate model objects, which means calling __init__
- so just getting an instance from the database will run into problems. Don't do this.
Instead, if you really need this to be provided by the model - even though it's just one line of code, as shown above - you could define a classmethod:
class Question(models.Model):
...
@classmethod
def query(cls, text):
question, _ = cls.objects.get_or_create(text=text, defaults={'asked': True})
return question
Then you could do Question.query('How are you')
and it would return either the new or the existing item.