Django OneToOneField with possible blank field Django OneToOneField with possible blank field django django

Django OneToOneField with possible blank field


If you want the after_homework field to be optional, then you should use null=True and blank=True.

class VideoGamePurchase(models.Model):    bought_by = models.ForeignKey(Person)    after_homework = models.OneToOneField(HomeWork, null=True, blank=True)

You don't want primary_key=True for the after_homework - that would make the after_homework the primary key field of the VideoGamePurchase model, which doesn't make sense if the field is optional.

It looks like your migrations are messed up because you had primary_key=True for the after_homework field earlier. The easiest fix would be to start with a fresh database, delete the migrations for that app, then rerun makemigrations and migrate. This time, the migration will automatically create a primary key field id for the VideoGamePurchase model.