django_filter ModelChoiceFilter auth.models.User外键to_field_name [英] django_filter ModelChoiceFilter auth.models.User ForeignKey to_field_name

查看:87
本文介绍了django_filter ModelChoiceFilter auth.models.User外键to_field_name的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用django_filter将过滤应用于模板(Django 1.11)中呈现的django_tables2.我要过滤的字段之一是内置用户模型中的ForeignKey:

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)

我的过滤器设置如下:

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

过滤工作正常,但不是过滤器下拉列表中显示的默认用户名",我想使用用户的全名: get_full_name

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!

推荐答案

好,我为此制定了解决方案.不知道这是正确的方法还是只是解决方法,但是无论如何对我来说都很好.

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.

将过滤器类型更改为ChoiceField:

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.

这篇关于django_filter ModelChoiceFilter auth.models.User外键to_field_name的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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