在wagtailadmin中使用limit_choices_to中的或Q()对象 [英] Using or Q() objects in limit_choices_to in wagtailadmin

查看:60
本文介绍了在wagtailadmin中使用limit_choices_to中的或Q()对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Django 1.10.5

Django 1.10.5

def limit_contributor_choices():
    limit = Q(group__name="contributor") | Q(group__name="Group")
    return limit


author = models.ForeignKey(
    settings.AUTH_USER_MODEL,
    blank=True, null=True,
    limit_choices_to=limit_contributor_choices,
    verbose_name=_('Author'),
    on_delete=models.SET_NULL,
    related_name='author_pages',
)

使用以下代码,如果用户在多个组中,则查询将多次返回该用户。我如何获得不同的值?

With the following code, if a user is in more than one group, then the query returns that user multiple times. How do I get distinct values?

我正在wagtail管理员中使用此值,系统会自动生成下拉列表。

I'm using this in the wagtail admin where the dropdown is generated automatically.

也许另一种看待它的方法是重写查询集并添加distinct()?如果是这样,我不确定如何在wagtailadmin中覆盖它。

Perhaps another way to look at it would be to override the queryset and add distinct()? If so, I'm not sure how to override that in wagtailadmin

推荐答案

一个可能的技巧是编译用户ID列表,然后将其作为过滤条件:

One possible trick is to compile a list of user IDs, and then return that as the filter criterion:

def limit_contributor_choices():
    allowed_user_ids = User.objects.filter(Q(group__name="contributor") | Q(group__name="Group")).values_list('id', flat=True)
    return Q(id__in=allowed_user_ids)

这篇关于在wagtailadmin中使用limit_choices_to中的或Q()对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆