Django:如何使用username__iexact默认过滤用户?

时间:2012-11-03 08:26:13

标签: python django orm

实施用户名不区分大小写:

我想在查询iexact时含蓄地暗示user

user = User.objects.get(username = 'yugal')  # Lowercase
user.id # 1

user = User.objects.get(username = 'YUgal')  # Mixcase
user.id # 1

我怎样才能做到这一点? {以某种方式UserManager}

注意:

  • 此外,django.shortcuts.get_object_or_404似乎将其用作User.objects.get_query_set().all().get()。我们怎样才能让它发挥作用?

2 个答案:

答案 0 :(得分:3)

明确的:

user = User.objects.get(username__iexact='yugal')

隐式:覆盖User模型,您可以覆盖objects属性,在其中添加自定义iexact处理:

class MyUser(User):

    class Meta:
        proxy = True


    objects = MyManager()


class MyManager(UserManager):

    def get(self, *args, **kwargs):

       if 'username' in kwargs:
           kwargs['username__iexact'] = kwargs['username']
           del kwargs['username']
       return super(MyManager, self).get(*args, **kwargs)

答案 1 :(得分:0)

我想我想出了一种为所有数据库查询实现它的方法:

###### QuerySet #######
def _filter_or_exclude(self, negate, *args, **kwargs):
    if 'username' in kwargs:
        kwargs['username__iexact'] = kwargs['username']
        del kwargs['username']
    if args or kwargs:
        assert self.query.can_filter(),\
        "Cannot filter a query once a slice has been taken."
    from django.db.models import Q
    clone = self._clone()
    if negate:
        clone.query.add_q(~Q(*args, **kwargs))
    else:
        clone.query.add_q(Q(*args, **kwargs))
    return clone

from django.db.models.query import QuerySet
QuerySet._filter_or_exclude = _filter_or_exclude
######################

这解决了这个问题。