问题描述
我添加了标签= TaggableManager(blank = True)给我的模型,但我希望我的标签不区分大小写。
我看到一些这样的工作片段,想问是否有一个简单的方法呢?
如果我必须从TaggableManager中重写一些方法,请告知我该怎么做?
提前感谢
Arshavski Alexander。 / p>
我已经使用出现类似的问题。代码副本(转载为后代):
from django.db.models import manager
from django。 db.models.query import QuerySet
class CaseInsensitiveQuerySet(QuerySet):
def _filter_or_exclude(self,mapper,* args,** kwargs):
#'name'是一个您的模型中的字段,您希望不区分大小写的搜索
如果kwargs中的name:
kwargs ['name__iexact'] = kwargs ['name']
del kwargs ['name ']
return super(CaseInsensitiveQuerySet,self)._ filter_or_exclude(mapper,* args,** kwargs)
#覆盖初始查询集的自定义管理器
class TagManager(Manager )
def get_query_set(self):
返回CaseInsensitiveQuerySet(self.model)
#和模型本身
class Tag(models.Model):
name = models.CharField(maxlength = 50,unique = True,db_index = True)
objects = TagManager()
def __str __(self):
return self.name
#now ...
>>> tag = Tag(name ='test')
>>> tag.save()
>>> Tag.objects.get(name ='TEST')
<标签:test>
基本上,您将覆盖初始查询集,以便所有查询器都会考虑不区分大小写的情况。
I added tags = TaggableManager(blank=True) to my models, but I want my tags to be case-insensitive.I saw some snippets of work arounds for this and wanted to ask if there is an easy way to do it?If I have to override some methods from the TaggableManager, please advise how can I do that?
Thanks in advance,Arshavski Alexander.
I have used this snippet for a similar issue. A copy of the code (reprinted for posterity):
from django.db.models import Manager
from django.db.models.query import QuerySet
class CaseInsensitiveQuerySet(QuerySet):
def _filter_or_exclude(self, mapper, *args, **kwargs):
# 'name' is a field in your Model whose lookups you want case-insensitive by default
if 'name' in kwargs:
kwargs['name__iexact'] = kwargs['name']
del kwargs['name']
return super(CaseInsensitiveQuerySet, self)._filter_or_exclude(mapper, *args, **kwargs)
# custom manager that overrides the initial query set
class TagManager(Manager):
def get_query_set(self):
return CaseInsensitiveQuerySet(self.model)
# and the model itself
class Tag(models.Model):
name = models.CharField(maxlength=50, unique=True, db_index=True)
objects = TagManager()
def __str__(self):
return self.name
# now...
>>> tag = Tag(name='test')
>>> tag.save()
>>> Tag.objects.get(name='TEST')
<Tag: test>
Basically, you override the initial queryset so that all querysets take case insensitivity into account.
这篇关于使用django-taggit创建不区分大小写的标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!