【问题标题】:Django get_or_create with icontains带有图标的 Django get_or_create
【发布时间】:2018-02-17 15:52:27
【问题描述】:

我在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" 的内容,我希望获得正确的团队,而不是创建大小写错误的重复团队。

【问题讨论】:

    标签: django


    【解决方案1】:

    正确的方法是使用 Django 的函数 get_or_create()。但是你应该使用“iexact”()而不是“icontains”,除非你想要一个完全匹配,在这种情况下你应该只使用“exact”:

    Team.objects.get_or_create(
        name__iexact=team_name,
        defaults = {
            "name": team_name
        }
    )
    

    在“默认值”之外,您应该输入搜索词。如果对象不存在,你应该在'defaults'中写下你的创建条款

    【讨论】:

      【解决方案2】:

      除了wencakisa 的答案之外的另一个选择是在get_or_create 中包含defaults 参数,因为Django 会剥离包含__ 分隔符的查找。查看this question的答案。

      代码是:

      Team.objects.get_or_create(
          name__icontains=team_name,
          defaults = {
              "name": team_name
          }
      )
      

      【讨论】:

        【解决方案3】:

        我认为在这里您应该拆分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.
        

        【讨论】:

        • 好点...没有意识到get_or_create 不允许icontains。最后,我还使用了iexact 而不是icontains,以避免在另一个名为“Golden Bears”的团队的情况下出现错误。
        猜你喜欢
        • 1970-01-01
        • 2011-01-18
        • 2018-02-12
        • 1970-01-01
        • 2015-06-09
        • 2017-11-05
        • 2018-05-12
        • 1970-01-01
        • 2016-11-18
        相关资源
        最近更新 更多