Search code examples
djangodjango-usersdjango-filter

django_filter ModelChoiceFilter auth.models.User ForeignKey to_field_name


I am using django_filter to apply filtering to django_tables2 rendered in my template (Django 1.11). One of the fields I would like to filter on is a ForeignKey from in-built User model:

class User(auth.models.User,auth.models.PermissionsMixin):

class Task(models.Model):
    assigned = models.ForeignKey(User,on_delete=models.DO_NOTHING)

My filter is setup as follows:

class TaskFilter(django_filters.FilterSet):
    assigned = django_filters.ModelChoiceFilter(queryset=User.objects.filter(is_staff=False),label=('Assigned'))

The filtering works fine but rather than the default "username" being displayed in the filter dropdown I would like to use the full name of the user: get_full_name

Does anyone have advice on how to acheive this? Any guidance will be much appreciated!


Solution

  • Ok I worked out a solution to this. Not sure if this is the correct way to do or just a work around but in any event it is working fine for me.

    Changed the filter type to ChoiceField:

    assigned = django_filters.ChoiceFilter(choices=get_full_names,label=('Assigned'))
    

    And populated the CHOICES using the following:

    def get_full_names():
        full_names = ()
        users = User.objects.filter(is_staff=False)
        for user in users:
            full_names += (user.id, user.get_full_name),
        return full_names
    

    Hopefully this helps someone else who has the same problem.