Using or Q() objects in limit_choices_to in wagtailadmin

左心房为你撑大大i 提交于 2019-12-14 03:53:09

问题


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?

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

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


回答1:


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)


来源:https://stackoverflow.com/questions/42572095/using-or-q-objects-in-limit-choices-to-in-wagtailadmin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!