python - 小写字段值 django 模型查询集

标签 python django django-models django-rest-framework django-taggit

我有一个对象的模型,并且为该模型的对象分配了几个标签。标签可以是大写、小写或两种大小写的混合。 我想编写一个查询集,它将返回具有与我提供的相同标签的对象。 注意:我正在使用 django-taggit 模块。
View .py

def home(request):
    book = Book.objects.filter(tags__name__in= map(lambda s:s.lower(), ['harry-potter', 'Champak', 'Physics']))
    print(book)
    return HttpResponse("Books Retrieved")

模型.py

from django.db import models
from django.utils.translation import ugettext_lazy as _

from taggit.managers import TaggableManager
from taggit.models import GenericUUIDTaggedItemBase, TaggedItemBase

class UUIDTaggedItem(GenericUUIDTaggedItemBase, TaggedItemBase):
    class Meta:
        verbose_name = _("Tag")
        verbose_name_plural = _("Tags")

class Book(models.Model):
    name = models.CharField(max_length=100)
    details = models.TextField(blank=True)
    tags = TaggableManager(through=UUIDTaggedItem, blank = True)

现在我想退回所有带有“哈利波特”、“哈利波特”或任何其他单词标签的图书。

PS:如果无论如何我们可以降低“tags__name__in”列表,我们的工作就完成了。

最佳答案

您可以创建一个 Q 对象,在其中过滤区分大小写的:

from django.db.models import <strong>Q</strong>

data = ['harry-potter', 'Champak', 'Physics']

qfilter = Q(
    *[<strong>Q(tags__name__iexact=item)</strong> for item in data],
    _connector=Q.OR
)

Book.objects.filter(
    <strong>qfilter</strong>
)

__iexact [Django-doc]将不区分大小写地与 data 中的每个 item 进行匹配。

关于python - 小写字段值 django 模型查询集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68920384/

相关文章:

c++ - Boost/Python 有 make_array 方法吗?

python - Django 1.7 多站点用户模型

django - 不可散列类型 : 'list' error when trying to add m2m relationships dynamically using post_save in Django

python - 以结尾的python单词中的字符串比较

python - 为什么在这种情况下 while 循环比 range 快得多?

python - Django:名称 'csrf_token' 未定义

python - 我在 django 中的评论表单不起作用?它既不向数据库发送数据也不显示这些数据?

python - 音频不播放。 Django,DEBUG = False

python - 使用 Django 通过模型字段定义 ManyToManyField 的顺序

python - 全屏我的Python Turtle Canvas而不修改大小