【问题标题】:django Filter customers in the specific user groupsdjango 过滤特定用户组中的客户
【发布时间】:2020-12-16 07:34:20
【问题描述】:

我想在 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()

【问题讨论】:

  • __in 需要两个扁平破折号而不是一个,这样可以解决问题吗?
  • @voodoo-burger - 抱歉打错了,但效果不佳
  • related_name 的使用在这里令人困惑。如果你删除它,运行迁移并使用user__groups__name__in
  • @voodoo-burger - 让我试试

标签: django usergroups


【解决方案1】:

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

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)

确保customers 具有usersusersyour_groups 的一部分

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-21
    • 2014-09-18
    • 2019-08-10
    • 1970-01-01
    • 2021-09-01
    • 1970-01-01
    • 2012-12-10
    • 2013-03-21
    相关资源
    最近更新 更多