简体   繁体   中英

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.

I have a model called Project and a model called UserProject. In the Userproject I have two foreign Keys pointing to a User and a Project.

What I tried was to use on_delete = CASCADE on the project-Foreign Key. This seems to only affect the Project-field in the Userproject model. So when I delete a Project which also has Userproject entries, those don't get deleted. 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. Try deleting a Project object from the admin panel, if there are associated cascade objects they should be displayed on the deletion confirmation page.

Since the project attribute can be set to null, this seems to describe the behavior you are seeing. CASCADE is used here correctly based on what we can see.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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