为什么Django on_delete规则不起作用? [英] Why is Django on_delete rule not working?

查看:287
本文介绍了为什么Django on_delete规则不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个通过ForeignKey进行连接的模型,如下所示:

I have two models connected via a ForeignKey sort of like this:

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)
    # ...

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

I'm writing a data migration where I try to delete some Albums:

# -*- 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 规则,因此我不得不遍历queryset并在每个实例上调用delete。但是显然这还不够。 on_delete 的意思是什么,即使这样也不起作用?有什么我可以做的吗?谢谢。

But the on_delete rule is there. Isn't the whole point of the delete rule to avoid errors like this? Or am I missing something? Initially I was trying a delete on the queryset, and I thought the on_delete rule wasn't supported and I had to loop through the queryset and call a delete on each instance. But apparently not even this is enough. What is the point of on_delete if even this doesn't work? Is there anything I can do? Thanks.

更新:在外壳程序中有效。我只会在迁移中遇到错误。

UPDATE: In the shell, it works. I only get the error in the migration.

推荐答案

您需要允许相册实际上为null:

You need to allow album to be null indeed:

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

这篇关于为什么Django on_delete规则不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆