更新时间: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.
pip install django-case-insensitive-field
创建一个 fields.py 文件
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)
# 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
仅此而已!