简体   繁体   English

Django - 删除外键时删除数据库条目

[英]Django - Delete db entry when ForeignKey was deleted

I am having trouble to solve this issue, even though I thought I understood the on_delete function.我在解决这个问题时遇到了麻烦,尽管我认为我理解 on_delete 函数。

I have a model called Project and a model called UserProject.我有一个名为 Project 的模型和一个名为 UserProject 的模型。 In the Userproject I have two foreign Keys pointing to a User and a Project.在 Userproject 我有两个外键指向一个用户和一个项目。

What I tried was to use on_delete = CASCADE on the project-Foreign Key.我尝试的是在项目外键上使用 on_delete = CASCADE 。 This seems to only affect the Project-field in the Userproject model.这似乎只影响 Userproject 模型中的 Project-field。 So when I delete a Project which also has Userproject entries, those don't get deleted.所以当我删除一个也有 Userproject 条目的项目时,那些不会被删除。 How could I achieve this?我怎么能做到这一点?

from django.db import models
from django.contrib.auth.models import User

# Create your models here.
class Project(models.Model):

    id = models.AutoField(db_column = 'db_ID', primary_key = True)
    name = models.CharField(max_length=500, default = None)
    descriptor = models.CharField(max_length = 1000, null = True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = 'projects'

    def __str__(self):
        return self.name




class Userproject(models.Model):
    id = models.AutoField(db_column = 'db_ID', primary_key = True)
    user = models.ForeignKey(User, on_delete= models.SET_NULL, null = True)
    project = models.ForeignKey('Project', on_delete = models.CASCADE,default = 1, null = True)
    created_at = models.DateTimeField(auto_now_add=True, null=True)
    updated_at = models.DateTimeField(auto_now=True, null = True)

    class Meta:
        db_table = 'UserProjects'
    def __str__(self):
        return self.id

It seems you may be deleting the project attribute from the Userproject attribute, but not deleting the Project itself.看来你可能会删除project从属性Userproject属性,但不能删除Project本身。 Try deleting a Project object from the admin panel, if there are associated cascade objects they should be displayed on the deletion confirmation page.尝试从管理面板中删除Project对象,如果有关联的级联对象,它们应该显示在删除确认页面上。

Since the project attribute can be set to null, this seems to describe the behavior you are seeing.由于project属性可以设置为空,这似乎描述了您所看到的行为。 CASCADE is used here correctly based on what we can see.根据我们所见,这里正确使用了CASCADE

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM