Search code examples
djangodjango-admin

Custom query for select field in Djnago admin


is it possible to make custom query for that field?

I have many users, I need to filter if by group to reduce the number of choices.

admin panel - select input

I didn't find anything except making custom query for whole models.

Any example would be enough for me.

I use build-in group model. And let's say, I want to see in User field only from group "Director" for model below.

class Invitation(models.Model):
    school = models.ForeignKey(School, on_delete=models.CASCADE)
    user = models.ForeignKey(User, on_delete=models.CASCADE)

For now, I use default: admin.site.register(Invitation)


Solution

  • If you want to do this application-wide, you can use limit_choices_to=… [Django-doc]:

    class Invitation(models.Model):
        school = models.ForeignKey(School, on_delete=models.CASCADE)
        user = models.ForeignKey(
            User,
            on_delete=models.CASCADE,
            limit_choices_to={'groups__name': 'Director'},
        )

    if you want to only apply this in the ModelAdmin you can limit the queryset by overriding the .formfield_for_foreignkey(…) [Django-doc]:

    @admin.site.register(Invitation)
    class InvitationAdmin(admin.ModelAdmin):
        def formfield_for_foreignkey(self, db_field, request, **kwargs):
            if db_field.name == 'user':
                kwargs['queryset'] = User.objects.filter(groups__name='Director')
            return super().formfield_for_foreignkey(db_field, request, **kwargs)

    Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation [Django-doc].