4

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

我想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(). 我们怎样才能让它发挥作用?
4

2 回答 2

4

明确的:

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)
于 2012-11-03T09:26:41.353 回答
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
######################

这解决了问题。

于 2012-11-03T11:07:57.240 回答