>>Team.objects.get(name__ico-6ren">
gpt4 book ai didi

Django get_or_create 与 icontains

转载 作者:行者123 更新时间:2023-12-05 08:55:24 26 4
gpt4 key购买 nike

我在 get_or_create 调用中使用 icontains 得到了意外结果。

举个例子:

>>>team_name = "Bears"
>>>Team.objects.get(name__icontains=team_name) # returns DoesNotExist as expected
>>>team, created = Team.objects.get_or_create(name__icontains=team_name)
>>>print(created) # Prints True as expected
>>>print(team.name) # Prints an empty string!

为什么这会创建一个名称为空而不是“Bears”的团队?我在这里使用 get_or_create 的原因是,如果后续用户发布类似 "BearS" 的内容,我想获得正确的团队,而不是创建一个大写字母不正确的重复团队.

最佳答案

我认为在这里您应该拆分 get()create() 功能而不是使用 get_or_create(),因为 __icontains 查找仅适用于 get()

尝试做这样的事情:

>>> team_name = 'Bears'

>>> teams = Team.objects.filter(name__icontains=team_name)
# This will filter the teams with this name

>>> team = teams.first() if teams.exists() else Team.objects.create(name=team_name)
# Now your team is the first element of your previous query (it returns a QuerySet with single element) if it exists
# Otherwise, you create a new Team.

关于Django get_or_create 与 icontains,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46121243/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com