开发者

Delete manytomanyfield in Django

开发者 https://www.devze.com 2022-12-29 15:03 出处:网络
I have the following models class Database(models.Model): user = models.ForeignKey(User) name = models.CharField(max_length=100)

I have the following models

class Database(models.Model):
    user = models.ForeignKey(User)
    name = models.CharField(max_length=100)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)


class DatabaseUser(models.Model):
    user = models.ForeignKey(User)
    name = models.CharField(max_length=100)
    password = models.CharField(max_lengt开发者_如何学JAVAh=100)
    database = models.ManyToManyField(Database)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

One DatabaseUser can have many Databases under it's control.

The issue I have if I go to delete a Database it wants to Delete the DatabaseUser also.. Is there a way to stop this from happening easily?


It's not clear why you have the multiple fks to User, but that aside you need to unhook the relationship between the Database and any DatabaseUsers

for db_user in yourdatabase.databaseuser_set.all(): #for all users who are linked to the DB you're about to kill
  db_user.database.remove(yourdatabase) #unhook the m2m

yourdatabase.delete()

[edit was typo fix]

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号