django - 为什么 Django on_delete 规则不起作用?

标签 django django-migrations

我有两个模型通过外键连接,如下所示:

class Album(models.Model):
    name = models.CharField(max_length=128)
    # ...

class Track(models.Model):
    name = models.CharField(max_length=128)
    album = models.ForeignKey(Album, related_name='tracks', null=True, on_delete=models.SET_NULL)
    # ...

我正在编写数据迁移,尝试删除一些相册:

# -*- coding: utf-8 -*-
# Generated by Django 1.9.13 on 2018-12-12 14:05
from __future__ import unicode_literals

from django.db import migrations


def forwards_func(apps, schema_editor):
    Album = apps.get_model("myapp", "Album")
    db_alias = schema_editor.connection.alias

    for album in Album.objects.using(db_alias).filter(foo='bar'):
        album.delete()

def reverse_func(apps, schema_editor):
    pass

class Migration(migrations.Migration):

    dependencies = [
        ('myapp', '0049_blabla'),
    ]

    operations = [
        migrations.RunPython(forwards_func, reverse_func),
    ]

但是,我收到此错误:

  File "/usr/local/lib/python2.7/site-packages/django/db/backends/base/base.py", line 211, in _commit
    return self.connection.commit()
IntegrityError: update or delete on table "Album" violates foreign key constraint "f2274d6f2be82bbff458f3e5487b1864" on table "Track"
DETAIL:  Key (id)=(1) is still referenced from table "Track".

但是 on_delete 规则是存在的。删除规则的全部目的不就是为了避免这样的错误吗?或者我错过了什么?最初,我尝试在查询集上删除,我认为不支持 on_delete 规则,我必须循环查询集并在每个实例上调用删除。但显然这还不够。如果这都不起作用,那么 on_delete 的意义何在?有什么我可以做的吗?谢谢。

更新:在 shell 中,它可以工作。我只在迁移时收到错误。

最佳答案

您确实需要允许album为空:

album = models.ForeignKey(Album, on_delete=models.SET_NULL, null=True)

关于django - 为什么 Django on_delete 规则不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53765114/

相关文章:

django - 文件 : "Upload a valid image" using Postman in Django Rest Framework

嵌套路由上的 Django REST 权限

python - django 1.7 makemigrations 需要我尝试删除的依赖项

django - 为什么 Django 中没有 "ListField"?

python - Django-sass-处理器类型错误

python - Django 模板 : get many-to-many value in formset

Django bool 字段 View +模板

python - 删除模型继承并将 id 保留在新创建的自动字段中

Python 2 -> 3 Django迁移导致字段参数类型改变

python - Django 迁移错误 : ERRORS: 'choices' must be an iterable (e. g.,列表或元组)