Given the following models:
class Poll(models.Model):
question = models.CharField(maxlength=200)
pub_date = models.DateTimeField('date published')
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice = models.CharField(maxlength=200)
votes = models.IntegerField()
you can do:
>>> what, created = Poll.objects.get_or_create(question='What?', pub_date='2006-12-09')
>>> django = what.choice_set.create(choice='Django', votes=100)
>>> python, created = Choice.objects.get_or_create(poll=what, choice='Python', votes=200)
But for some reason this doesn't work:
>>> php, created = what.choice_set.get_or_create(choice='PHP', votes=1)
but gives the following error and traceback:
<class 'sqlite3.IntegrityError'> Traceback (most recent call last)
django/db/models/manager.py in get_or_create(self, **kwargs)
68
69 def get_or_create(self, **kwargs):
---> 70 return self.get_query_set().get_or_create(**kwargs)
71
72 def create(self, **kwargs):
django/db/models/query.py in get_or_create(self, **kwargs)
238 params.update(defaults)
239 obj = self.model(**params)
--> 240 obj.save()
241 return obj, True
242
django/db/models/base.py in save(self)
202 cursor.execute("INSERT INTO %s (%s) VALUES (%s)" % \
203 (backend.quote_name(self._meta.db_table), ','.join(field_names),
--> 204 ','.join(placeholders)), db_values)
205 else:
206 # Create a new record with defaults for everything.
django/db/backends/util.py in execute(self, sql, params)
10 start = time()
11 try:
---> 12 return self.cursor.execute(sql, params)
13 finally:
14 stop = time()
django/db/backends/sqlite3/base.py in execute(self, query, params)
90 def execute(self, query, params=()):
91 query = self.convert_query(query, len(params))
---> 92 return Database.Cursor.execute(self, query, params)
93
94 def executemany(self, query, param_list):
<class 'sqlite3.IntegrityError'>: testing_choice.poll_id may not be NULL