为什么Django on_delete规则不起作用



我有两个模型通过ForeignKey连接,类似于这样:

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规则是存在的。删除规则的全部目的不是为了避免这样的错误吗?还是我错过了什么?最初,我在查询集上尝试delete,但我认为on_delete规则不受支持,我必须循环查询集,并在每个实例上调用delete。但显然这还不够。如果连on_delete都不起作用,那它有什么意义呢?我能做什么吗?谢谢

UPDATE:在shell中,它是有效的。我只在迁移中得到错误。

您确实需要允许album为空:

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

最新更新