【问题标题】:Why is Django on_delete rule not working?为什么 Django on_delete 规则不起作用?
【发布时间】:2018-12-13 15:27:19
【问题描述】:

我有两个通过 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 规则不受支持,我不得不遍历查询集并在每个实例上调用删除。但显然这还不够。如果连这都不起作用,on_delete 的意义何在?有什么我可以做的吗?谢谢。

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

【问题讨论】:

    标签: django django-migrations


    【解决方案1】:

    您需要允许 album 确实为空:

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

    【讨论】:

    • 对不起,这只是我实际设置的简化版本,我忘了添加这个细节。我编辑了问题并添加了它。它仍然不起作用,即使使用null=True :(
    • 哦,好的。您是否尝试过在迁移之外做同样的事情?例如来自 django shell?结果一样吗?
    • 刚刚试了,效果很好。为什么它在迁移中不起作用?有什么想法吗?
    • 前几天刚刚遇到了类似的行为。 This part of the documentation 似乎可以解释这种行为。
    猜你喜欢
    • 1970-01-01
    • 2018-11-03
    • 2019-01-08
    • 2015-02-26
    • 2015-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-16
    相关资源
    最近更新 更多