嗨,我是python的新手,第一次在mysql中实现ORM。
下面是我们用于创建模型的代码
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
我们正在尝试获取与Roles
关联的所有User
,但它为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
settings.py
AUTH_USER_MODEL = "login_api.User"
答案 0 :(得分:0)
访问特定的模型实例(而不是模型的管理器)时,可以使用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/