gpt4 book ai didi

python - django 数据库模型中的多对多关系

转载 作者:行者123 更新时间:2023-12-02 04:27:52 25 4
gpt4 key购买 nike

嗨,我对 python 完全陌生,并且是第一次在 mysql 中实现 ORM。

我们有三个两张表和一个中间表,如下图所示
many to many relationship

下面是我们用来创建模型的代码

class Roles(models.Model):
"""
A class that stores all the types of roles that are available to the user
"""
role_id = models.CharField(max_length=200, blank=False,primary_key=True)
role_name = models.CharField(max_length=200)

class Meta:
db_table = 'roles'
managed = False


class User(AbstractBaseUser):
# class ChannelUser(models.Model):
"""
An abstract base class implementing a fully featured User model with
admin-compliant permissions.

"""
user_id = models.CharField(max_length=200, blank=False,primary_key=True)
user_email = models.EmailField(max_length=200, blank=False, unique=True)
roles=models.ManyToManyField(
Roles,
through='UserRole',
# through_fields=('user_id', 'role_id'),
)

USERNAME_FIELD = 'user_email'

class Meta:
db_table = 'user'
managed = False

class UserRole(models.Model):
"""
A class that stores user ids and role ids
"""
user = models.ForeignKey(User, on_delete=models.PROTECT, db_column='user_id')
role = models.ForeignKey(Roles, on_delete=models.PROTECT, db_column='role_id')
timestamp = models.DateTimeField(default=timezone.now)

class Meta:
db_table = 'user_roles'
managed = False

我们正在尝试获取所有 RolesUser 相关联,但它为 roles 提供 None .

我不确定,我们在这里做错了什么。有人可以指出。

下面是我用来获取角色的代码
user_detail = User.objects.get(user_email=username)
print(user_detail.user_email) //prints user email
print(user_detail.roles) // prints Roles.None

设置.py
AUTH_USER_MODEL = "login_api.User"

最佳答案

当访问特定模型实例(而不是模型的管理器)时,您可以使用 modelname_set 访问相关项目。而不是 modelname .例如:

>>> user_detail.roles_set.remove(my_role)
>>> user_detail.roles_set.all()
<QuerySet []>

文档:

https://docs.djangoproject.com/en/2.1/topics/db/examples/many_to_many/

关于python - django 数据库模型中的多对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52169137/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com