You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

执行python manage.py makemigrations报错:ForeignKey缺失on_delete参数

Fixing the "TypeError: init() missing 1 required positional argument: 'on_delete'" in Django 2.0.1

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 the author field to NULL when the user is deleted—you'll need to add null=True to 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 a default value for the field
  • models.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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:41:13