18 thoughts on “How to make a Django ForeignKey optional”

  1. Thanks, that just helped me a bunch!

    I also noticed I had to redefine the foreign key column in my database (MySQL) to accept NULL values, since it had already been created before I added null=True:

    alter table articles_article change category_id category_id integer NULL;

  2. Just when you need the information quickly without too much waffle, up pops a blog like this and does just the job – many thanks! Stretch’s comment helped as well, since I had already created the table without the null-accepting columns.

  3. Thanks. Also if manage.py synchdb doesn’t work you should drop all those tables by doing a python.exe manage.py sqlclear appname > droptables.sql

    shell> mysql -u userid -p DBName < droptables.sql

  4. As people still seem to use this rather old blog post, let me clarify something:

    null=True refers to the database representation of the model.
    blank=True refers to the behavior of the field in ModelForms.

    So, while null=True means that you the database accept null-values for this column, form validation will still fail. Separating form and model behavior is necessary because you might to do something like default=’something’ which is only used, when the value from the form is None.

    Anyway, setting null=True is enough to get rid of the IntegrityError as of 1.4 at least.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>