Django-基于用户权限或用户组名称的数据查询

时间:2019-08-30 01:50:06

标签: python django django-queryset

我是Python的新手,并开始了一个项目,在该项目中,我列出了分布在世界各地的客户。系统用户只能访问自己区域内的用户

我为客户类添加了自定义权限。

我正在尝试找到一种基于身份验证组名称或用户权限列出所有客户的一个或多个区域(例如latam,emea,us等)的方法。有可能吗?

views.py

class CustomerListView(PermissionRequiredMixin, LoginRequiredMixin, generic.ListView):
    model = Customer
    context_object_name = 'customers'
    template_name = 'customers/customer.html'
    login_url = '/'
    permission_required = 'customer.view_customer'
    permission_denied_message = 'User has no permission to perform this action.'

model.py

class Region(models.Model):
    region_id = models.AutoField(primary_key=True)
    region_name = models.CharField(max_length=12, unique=True)


def __str__(self):
    return self.region_name


class Customer(models.Model):
    class Meta:
        permissions = (
            ("latam_view", "Can acceess LATAM data"),
            ("us_view", "Can acceess US data"),
            ("emea_view", "Can acceess EMEA data"),
        )
    customer_id = models.AutoField(primary_key=True)
    customer_name = models.CharField(max_length=15, null=False, blank=False, unique=True)
    primary_contact_name = models.CharField(max_length=24, null=False, blank=False)
    primary_contact_position = models.CharField(max_length=25, null=False, blank=False)
    primary_contact_department = models.CharField(max_length=15, null=False, blank=False)
    primary_contact_phone = models.CharField(max_length=17, null=False, blank=False)
    primary_contact_email = models.EmailField(max_length=30, null=False, blank=False)
    customer_region = models.ForeignKey(Region, on_delete=models.PROTECT, null=False, blank=False)
    auth_group = models.ForeignKey(Group, on_delete=models.PROTECT, null=False, blank=False)

def __str__(self):
    return self.customer_name

谢谢

1 个答案:

答案 0 :(得分:0)

如果您只是在学习,建议您简化一下。

型号:

class Customer(model.Models):
    is_latam = models.BooleanField(default=False)
    is_us = models.BooleanField(default=False)
    is_emea = models.BooleanField(default=False)
    other_fields = models.IntegerField(default=0)

查看:

def view_customer(request):
    return render(request, 'template.html', {customers: Customer.objects.all()})

模板:

{% for customer in customers %}
    {% if customer.is_latam %}
    Latam Data here
    {% endif %}
    {% if customer.is_us %}
    US Data here
    {% endif %}
    {% if customer.is_emea %}
    Emea Data here
    {% endif %}
{% endfor %}

希望这有助于引导您朝正确的方向前进!