Dafonz
Dafonz

Reputation: 41

Using or Q() objects in limit_choices_to in wagtailadmin

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

Upvotes: 4

Views: 1714

Answers (1)

gasman
gasman

Reputation: 25292

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)

Upvotes: 3

Related Questions