执行python manage.py makemigrations报错:ForeignKey缺失on_delete参数
Hey there! I totally get why this error feels confusing as a beginner—let's break it down step by step so you understand exactly what's going on and how to fix it.
What's causing the error?
Starting with Django 2.0, the ForeignKey field requires you to explicitly define the on_delete parameter. In older Django versions (1.x), this parameter had a default value (CASCADE), but the Django team made it mandatory in 2.0 to force developers to think about what should happen to your blog posts when the associated user (the author) gets deleted.
Your current code in blog/models.py looks like this:
author = models.ForeignKey('auth.User')
Since you're using Django 2.0.1, this is missing the required on_delete argument, hence the TypeError.
How to fix it
You just need to add the on_delete parameter to your ForeignKey definition. The most common choice is models.CASCADE, which means if the user is deleted, all their blog posts will be deleted too. Here's the corrected line:
author = models.ForeignKey('auth.User', on_delete=models.CASCADE)
A quick breakdown of common on_delete options
To help you pick the right one for your project, here are some useful options:
models.CASCADE: Delete the blog post when the author is deleted (most intuitive for a blog)models.PROTECT: Prevent deleting the author if they have existing blog posts (throws an error if you try)models.SET_NULL: Set theauthorfield toNULLwhen the user is deleted—you'll need to addnull=Trueto the field too, like:author = models.ForeignKey('auth.User', on_delete=models.SET_NULL, null=True)models.SET_DEFAULT: Set the author to a predefined default user—you'll need to set adefaultvalue for the fieldmodels.DO_NOTHING: Leave the field as-is, but this can cause database constraint errors (not recommended unless you know exactly what you're doing)
Once you update your model, re-run the command:
python manage.py makemigrations blog
It should work without errors now!
内容的提问来源于stack exchange,提问作者J Gee

