我正在尝试为定义用户访问权限的外部组制作一个API。 我在 django 中有一个设置,可以轻松管理,但我希望输出对于其他团队来说非常简单。
这是我正在寻找的输出
,如下所示:{
"user_list": {
"user": {
"username": "username1",
"top_accesses": ["top_access_1", "top_access_2", "top_access_5"],
"middle_accesses": ["middle_access_1", "middle_access_2", "middle_access_7"],
"lower_accesses": ["lower_access_1", "lower_access_2", "lower_access_22"],
},
"user": {
"username": "username2",
"top_accesses": ["top_access_1", "top_access_2", "top_access_8"],
"middle_accesses": ["middle_access_3", "middle_access_5", "middle_access_6"],
"lower_accesses": ["lower_access_21", "lower_access_33", "lower_access_36"],
}
}
}
但是,我在使用 django 内置的 ORM 从我的模型中提出这些集合时遇到了麻烦。 我可以想到如何在SQL中做到这一点,但这不是一个特别干净的方法。 我知道一定有更好的方法可以做到这一点,因为使用 TabularInline 可以准确地显示我想在管理页面中看到的内容
这是我的模型:
class TopAccess(models.Model):
name = models.CharField(max_length=100)
site_user_access = models.ManyToManyField(User, blank=True)
site_group_access = models.ManyToManyField(Group, blank=True)
class Meta:
verbose_name_plural = "Top Access"
def __str__(self):
return self.name
class MiddleAccess(models.Model):
name = models.CharField(max_length=100)
site_user_access = models.ManyToManyField(User, blank=True)
site_group_access = models.ManyToManyField(Group, blank=True)
class Meta:
verbose_name_plural = "Middle Access"
def __str__(self):
return self.name
class LowerAccess(models.Model):
name = models.CharField(max_length=100)
site_user_access = models.ManyToManyField(User, blank=True)
site_group_access = models.ManyToManyField(Group, blank=True)
class Meta:
verbose_name_plural = "Lower Access"
def __str__(self):
return self.name
理想情况下,我将能够返回一个最终与 django-rest-framework 配合良好的查询对象,因为我喜欢它以任何请求的形式返回相同数据的方式
编辑: 这就是我认为接近解决方案的原因,但我知道我错误地使用了类继承
class MaybeThisCouldWork(User):
t_user = TopAccess.objects.filter(site_user_access=User)
m_user = MiddleAccess.objects.filter(site_user_access=User)
l_user = LowerAccess.objects.filter(site_user_access=User)
user_groups = User.objects.filter(id=User)
for user_group in user_groups:
t_group = TopAccess.objects.filter(
site_group_access=user_groups
)
m_group = MiddleAccess.objects.filter(
site_group_access=user_groups
)
l_group = LowerAccess.objects.filter(
site_group_access=user_groups
)
t_user = t_user | t_group
m_user = m_user | m_group
l_user = l_user | l_group
你可以使用序列化程序,可能是这样的,
class TopAccessSerializer(serializers.ModelSerializer):
class Meta:
model = TopAccess
fields = ['name']
class MiddleAccessSerializer(serializers.ModelSerializer):
class Meta:
model = MiddleAccess
fields = ['name']
class LowerAccessSerializer(serializers.ModelSerializer):
class Meta:
model = LowerAccess
fields = ['name']
class UserSerializer(serializers.ModelSerializer):
topaccess = TopAccessSerializer(source='topaccess_set', many=True)
middleaccess = MiddleAccessSerializer(source='middleaccess_set', many=True)
loweraccess = LowerAccessSerializer(source='loweraccess_set', many=True)
class Meta:
model = User
fields = ['username', 'topaccess', 'middleaccess', 'loweraccess']