Django使用icontains获取或创建
在我的Django使用icontains获取或创建,django,Django,在我的get\u或\u 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_n
get\u或\u 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!
为什么这会创建一个空白名称而不是“熊”的团队?我在这里使用
get\u或
的原因是,如果后续用户发布类似“BearS”
的内容,我希望获得正确的团队,而不是创建一个大写不正确的重复团队。我认为这里应该拆分get()
和create())
功能,而不是使用get\u或
,因为\u图标包含的查找仅适用于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.
我认为在这里您应该拆分get()
和create()
功能,而不是使用get\u或
,因为\u 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.
除了wencakisa的答案之外,另一个选项是在get\u或\u create
中包含defaults
参数,因为Django会剥离包含\u
分隔符的查找。请参阅的答案
守则是:
Team.objects.get_or_create(
name__icontains=team_name,
defaults = {
"name": team_name
}
)
除了wencakisa的答案之外,另一个选项是在get\u或\u create
中包含defaults
参数,因为Django会剥离包含\u
分隔符的查找。请参阅的答案
守则是:
Team.objects.get_or_create(
name__icontains=team_name,
defaults = {
"name": team_name
}
)
正确的方法是使用Django的函数get_或_create()。但是你应该使用“iexact”()而不是“icontains”,除非你想要一个精确的匹配,在这种情况下,你应该只使用“精确”:
在“默认值”之外,您应该放置搜索词。如果对象不存在,则应将创建术语写入“默认值”中。正确的方法是使用Django的函数get\u或\u create()。但是你应该使用“iexact”()而不是“icontains”,除非你想要一个精确的匹配,在这种情况下,你应该只使用“精确”:
在“默认值”之外,您应该放置搜索词。如果对象不存在,您应该在“默认值”中写入您的创建术语。好的观点…没有意识到get\u或\u create
不允许icontains
。例如,我还使用了iexact
而不是icontains
,以避免在另一个团队被称为“金熊”的情况下出现错误。很好的一点……我没有意识到get\u或\u create
不允许icontains
。我还使用了iexact
而不是icontains
,以避免出现错误,例如,有一个不同的团队被称为“金熊”。