Tortoise-orm: [Question] How can I choose how to delete data in a many-to-many relationship?

Created on 22 Sep 2020  路  7Comments  路  Source: tortoise/tortoise-orm

I have a Role table and a User table, related to a many to many relationship. What I want is that if I delete a role, not all the users with that role are deleted.

enhancement

Most helpful comment

Current not support.

All 7 comments

What's your models struct?

The model is:

class User(models.Model):
    username = fields.CharField(unique=True, max_length=255)
    password = fields.TextField()
    roles = fields.ManyToManyField(
        "models.Rol", related_name="users", through="user_rol"
    )


class Rol(models.Model):
    name = fields.TextField()
    description = fields.TextField(null=True)
    users: fields.ManyToManyRelation[User]

It don't delete user now when you delete role already, is it?

My problem is the "cascade" on_delete, I wish configure the SET_NULL for this relation many to many. it is possible?

Current not support.

Think after, I think you can define many-to-many relation yourself:

class User(Model):
    username = fields.CharField(unique=True, max_length=255)
    roles = fields.ManyToManyField(
        "models.Role", related_name="users", through='roleuser'
    )


class Role(Model):
    name = fields.TextField()
    users: fields.ManyToManyRelation[User]


class RoleUser(Model):
    user = fields.ForeignKeyField('models.User', on_delete=RESTRICT)
    role = fields.ForeignKeyField('models.Role', on_delete=RESTRICT):

Thanks, I'll try!

Was this page helpful?
0 / 5 - 0 ratings