问题描述
Django 没有不区分大小写的模型字段,那么如何在不破坏现有代码的情况下使模型字段不区分大小写?例如:我的 UserModel
上有一个 username
字段,但我注意到尽管使该字段唯一,但它仍然允许我使用相同单词的大小写变体:
Django do not come with case insensitive model field so how do I make a model field case insensitive without breaking my existing codes? For example: I have a username
field on my UserModel
but I noticed that despite making the field unique it would still allow me to use the case variant of the same word:
示例如下:
from django.db import models
class UserModel(models.Model):
username = models.CharField(max_length=16, unique=True)
user1 = UserModel(username='user1') # will go through
user1.save()
user2 = UserModel(username='User1') # will still go through
user2.save()
推荐答案
有很多方法可以解决这个问题,但我会推荐使用 .
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.
- 从 pypi.org 安装
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
仅此而已!
这篇关于如何实现 Django 不区分大小写的模型字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!