When multi-level many to many association is used, how can I get the lowest level data directly through the top level? For example, the user table, the user many to many association role table, the role table, and the many to many association menu table, how can I get all the menus directly according to the user object and serialize them to return to the front end. At present, I have implemented the method roles () to get all the roles according to the current user object in the user model, and the method menus () to get all the menus according to the current role object in the role model. How can I get all the menus directly according to the user object and how can I do it in the user model? I tried to find out all the roles first, then traverse the role to get out, and then get all the menus through the role, and finally put all the menus in a list, but this operation is not beautiful at all. The most kind of data I get is an ordinary list, not a queryset, which can't be serialized. I don't know if there is black technology in Django to complete this kind of thing, Ask the great God to answer
class UserInfo(models.Model):
uid = models.CharField(max_length=32, unique=True, default=gen_id)
username = models.CharField(max_length=32, unique=True)
password = models.CharField(max_length=256, blank=False, null=False)
status = models.IntegerField(default=1)
create_time = models.DateTimeField(default=now)
update_time = models.DateTimeField(default=now)
class Meta:
db_table = 'user'
def roles(self):
"""
反查当前用户所有角色列表
:return:
"""
roles = self.role_set.all()
if len(roles) > 0:
return roles
return []
class Role(models.Model):
role_code = models.CharField(max_length=10, unique=True, null=False)
role_name = models.CharField(max_length=10, unique=True, null=False)
role_desc = models.CharField(max_length=50, null=False)
status = models.IntegerField(default=1)
users = models.ManyToManyField(UserInfo)
class Meta:
db_table = 'role'
verbose_name = '角色表'
verbose_name_plural = '角色表'
def menus(self):
menus = self.menu_set.all()
if len(menus) > 0:
return menus
return []
class Menu(models.Model):
name = models.CharField(max_length=10, unique=True, null=False)
icon_class = models.CharField(max_length=10, null=True)
status = models.IntegerField(default=1)
roles = models.ManyToManyField(Role)
class Meta:
db_table = 'menu'
verbose_name = '菜单表'
verbose_name_plural = '菜单表'