How to make a Django ForeignKey optional

Looks like you need to have both blank=True and null=True to make a ForeignKey optional in a django model…

Tags:

15 Responses to “How to make a Django ForeignKey optional”

  1. Italo Maia says:

    Thanks ; )

  2. Paul Holt says:

    Thanks Rachel

  3. Beau says:

    Rachel, pretty awesome tip, thanks!!

  4. stretch says:

    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;

  5. Vinay says:

    Awesome, I was looking exactly for how to do this, and found this blog entry. It worked like a charm. Thanks a ton.

  6. Steve Androulakis says:

    Thanks for this! Helped a lot.

  7. Brenton says:

    Thanks Rachel, that was annoying me to no end!

  8. Dave says:

    Me too, saved! Thanks!

  9. Michael says:

    Thanks a bunch, Stretch was what I needed

  10. Harshad says:

    Thanks :-)

  11. Pablo says:

    Its not working for me, i still get an integrity error

  12. ??? says:

    syncdb again ^^

  13. Sebastian says:

    Great tip!

  14. daijones says:

    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.

  15. Carlos says:

    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

Leave a Reply