且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何实现 Django 不区分大小写的模型字段?

更新时间:2022-12-18 13:39:42

有很多方法可以解决这个问题,但我会推荐使用 django-case-insensitive-field"https://pypi.org/project/django-case-insensitive-field/" rel="nofollow noreferrer">pypi.org.

There a lot of approaches to solve this problem but I will recommend using django-case-insensitive-field from pypi.org.

这个包没有依赖,而且很轻.

The package has no dependency and it's light.

  1. 从 pypi.org 安装

pip install django-case-insensitive-field

  1. 创建一个 fields.py 文件

  1. Create a fields.py file

向您希望不区分大小写的 Field 添加一个 Mixin.下面的例子:

Add a Mixin to the Field you want to make case insensitive. Example below:


# fields.py

from django_case_insensitive_field import CaseInsensitiveFieldMixin
from django.db.models import CharField

class LowerCharField(CaseInsensitiveFieldMixin, CharField):
    """[summary]
    Makes django CharField case insensitive \n
    Extends both the `CaseInsensitiveFieldMixin` and  CharField \n
    Then you can import 
    """

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

        super(CaseInsensitiveFieldMixin, self).__init__(*args, **kwargs)

  1. 在模型/代码中的任何地方使用新字段


# models.py

from .fields import LowerCharField


class UserModel(models.Model):

    username = LowerCharField(max_length=16, unique=True)

user1 = UserModel(username='user1') # will go through


user2 = UserModel(username='User1') # will not go through

仅此而已!