django 过滤特定用户组中的客户

django Filter customers in the specific user groups

我想在 ListView 中显示来自特定组的客户,无法理解如何获取查询集

class CustomerList(ListView):
  model = Customer
  queryset = Customer.objects.filter(member__groups__name__in=['online', 'whatsapp'])
  template_name = 'customer/customer_list.html'

models.py

class Customer(models.Model): 
    member = models.ForeignKey(User, verbose_name=_("Customer"), on_delete=models.CASCADE)
    contact = models.ForeignKey(Contact, verbose_name=_("Contact"), on_delete=models.CASCADE, blank=True, null=True)
    ...

客户被添加到以下组中:

class AddUser(CreateView):
  def post(self, request, *args, **kwargs):
     form = UserForm(request.POST) 
     if form.is_valid(): 
        user = form.save(commit=False)
        group, created = Group.objects.get_or_create(name='online')
        user.groups.add(group)
        user.save()

我有类似的代码,检查这是否适合你 -

class ProfessorsList(generic.list.ListView):
  model = Staff
  queryset = Staff.objects.filter(member__groups__name='teaching')

对于多个组,您可以这样做:(我相信您已经在这样做了...)

Customer.objects.filter(member__groups__name__in=['online', ...])

如果它仍然对您不起作用,请尝试以下操作:

  users = User.objects.filter(groups__name__in=[your_groups])
  queryset = Customer.objects.filter(member__in=users)

确保 customersusersusersyour_groups

的一部分