基于M2M对象的权限的组

时间:2022-06-01 14:38:16

I'm not 100% sure if this is just a terrible design on my part, or I'm not thinking clearly.

如果这对我来说只是一个可怕的设计,或者我没有想清楚,我不是百分百肯定的。

I'm utilising the Group model with a m2m relationship to allowed_groups on my Category model.

我在我的Category模型上使用与m2m关系的Group模型与allowed_groups。

class Category(models.Model):
    """Forums are separated into Categories. A Category may hold many Forums"""
    name = models.CharField(max_length=80)
    position = models.IntegerField(blank=True, default=0)
    allowed_groups = models.ManyToManyField(
        Group,
        blank=True,
        null=True,
        help_text="Select what usergroups are able to see this forum.",
        related_name='forum_categories',
    )

    class Meta:
        ordering = ['position']
        verbose_name = 'Category'
        verbose_name_plural = 'Categories'

    def __unicode__(self):
        return u'%s' % self.name

I originally attempted this with a m2m to the User model, however I quickly came to realise that it would become very tedious assigning what Category instances a User would be able to see every time a new User registered.

我最初尝试使用m2m到用户模型,但我很快意识到,每次新用户注册时,分配用户可以看到的类别实例将变得非常繁琐。

What I'm trying to achieve, is get the Category instances that a User should be able to see defined by what Group they are in. The problem being, that they could potentially be within more than 1 Group at any given time.

我想要实现的是获取用户应该能够看到的类别实例,这些实例由他们所在的组定义。问题是,在任何给定时间,他们可能在多于1个组内。

I've tried to utilise the reverse forum_categories however if they are in more than one group it returns duplicates of Category.

我已经尝试使用反向forum_categories但是如果它们在多个组中,则返回Category的重复项。

1 个解决方案

#1


1  

distinct() method removes duplicate categories from queryset. Try this:

distinct()方法从queryset中删除重复的类别。尝试这个:

Category.objects.distinct().filter(allowed_groups__in=user.groups.all())

#1


1  

distinct() method removes duplicate categories from queryset. Try this:

distinct()方法从queryset中删除重复的类别。尝试这个:

Category.objects.distinct().filter(allowed_groups__in=user.groups.all())