我是 Tortoise ORM 的新手,一直在尝试为用户/组/角色实现一个简单的多对多模型
我试过的:
- 模型.py
from tortoise.models import Model
from tortoise import fields
class User(Model):
id = fields.IntField(pk=True)
email = fields.CharField(max_length=255, unique=True)
password = fields.CharField(max_length=255)
def __str__(self):
return self.email
class Group(Model):
id = fields.IntField(pk=True)
name = fields.CharField(max_length=255)
members = fields.ManyToManyField("models.User", related_name="users", through="Membership")
def __str__(self):
return self.name
class Membership(Model):
user = fields.ForeignKeyField("models.User")
group = fields.ForeignKeyField("models.Group")
role = fields.CharField(max_length=255)
- 主文件
from tortoise import Tortoise, run_async
from models import User, Group, Membership
async def init():
await Tortoise.init(
db_url='sqlite://db.sqlite3',
modules={'models': ['models']}
)
# Generate the schema
await Tortoise.generate_schemas()
# Test
new_user1 = await User.create(email="a@a.com",password="aa")
new_user2 = await User.create(email="b@b.com",password="bb")
new_user3 = await User.create(email="c@c.com",password="cc")
new_group1 = await Group.create(name="group1")
new_group2 = await Group.create(name="group2")
要创建会员链接,我尝试使用 add() 但这失败了,因为我无法在关联表中合并额外的“角色”字段
await new_group1.members.add(new_user1)
结果出错
tortoise.exceptions.IntegrityError: NOT NULL constraint failed: membership.role
我试过直接创建会员
await Membership.create(user_id=new_user1.id, group_id=new_group1.id, role="member")
await Membership.create(user_id=new_user2.id, group_id=new_group1.id, role="admin")
await Membership.create(user_id=new_user1.id, group_id=new_group2.id, role="member")
这有效,我已经能够检索每个组中的用户
groups = await Group.all()
for i in groups:
print(await i.members.all())
这使
[<User: 1>, <User: 2>]
[<User: 1>]
但是,我不知道如何检索关联表中用户的角色(会员)
感谢尝试实施此模型的任何帮助
- 是否可以使用 add() 在组中添加新用户并指定角色?
- 检索组中的用户列表时,如何检索成员中用户的角色?
谢谢,肯尼斯