【问题标题】:DoesNotExist: Customer matching query does not exist (Django)DoesNotExist:客户匹配查询不存在(Django)
【发布时间】:2014-09-22 12:46:51
【问题描述】:

在我的 Django 应用程序中,我收到“DoesNotExist:客户匹配查询不存在”,其中堆栈跟踪指出,当尝试从组的客户(客户可以有多个组)查询信息时,链接资源“不存在”但客户确实存在于数据库中(并且具有所要求的信息):

 class Group(models.Model):
      id = models.AutoField(primary_key=True)
      customer = models.ForeignKey(Customer, to_field="customer_id", related_name='groups', null=True, blank=True) ## a blank customer_id indicates the group is 'private'
      ...

     @property
     def groups_linked(self):

        if self.is_private:
             linked = False
        else:
             linked = Customer.objects.value_list('cross-group-collaboration', flat=True).get(pk=self.customer_id) ## here the error bubbles up saying the Customer does not exist!

        if linked:
              return {'customer_id' : self.customer_id }
         else:
              return group = { 'group_id' : self.if}

来自Django docs 对该错误的描述如下:“注意使用get() 和使用带有[0] 切片的filter() 之间存在区别。如果没有匹配的结果查询时,get() 将引发 DoesNotExist 异常。此异常是正在执行查询的模型类的属性 - 所以在上面的代码中,如果没有主键为 1 的 Entry 对象,Django 将引发 Entry.DoesNotExist。”

如果信息确实存在,但触发了上述错误,可能是什么原因造成的?

【问题讨论】:

  • 在您的 shell 或代码本身中,只需运行 Customer.objects.value_list('private', flat=True).count() - 我的猜测是,计数为 0。此外,.get() 仅适用于 filter 仅当有 1 个元素时。如果有 > 1,则会导致MultipleObjectsReturned 异常
  • 不,有返回计数。是的,当我探索并运行 SQL 命令SELECT 'customer'.'cross-group-collab' FROM 'customer' WHERE 'customer'.customer_id = <customer number>; 时,只有 一个 匹配项。由于关系是单向的,一个客户可以有多个组,但组只能属于一个客户,因此给定组不可能返回多个客户。
  • 是'cross-group-collaboration'还是'cross-group-collab'?
  • 另外,您可以使用(在这种情况下)self.customer 直接访问相关的(外键)模型实例
  • 我的错 - 这是跨组协作。

标签: python django django-orm


【解决方案1】:

我不确定您要在这里实现什么,但无论如何都没有必要去寻找 Customer 对象,因为您已经拥有它作为 self.customer

怎么样:

@property
def groups_linked(self):
    if self.customer is not None:
        return {'customer_id': self.customer.id}
    else:
        return {'group_id': self.id}

【讨论】:

  • customer_id 是链接我的组和客户表的外键。由于组可以是私有的,因此无需检查组是否可以跨组协作(基本上他们可以与客户拥有的其他组一起工作)。
  • @Robin:您甚至可以通过测试self.customer_id 来使其更简单,这样可以避免无用的查询。
  • 如果组是私有的,groups_linked 将为 false,即它是一个私有组。客户是帐户持有人,也有帐户登录,都与客户相关联,但帐户可以有私人组。这里的问题是一个组,它不是私人的,并且能够进行“跨组协作”(例如与公共组的客户列表中的其他组共享信息),在 .get( ) 查询(但在数据库中,客户 ID 与组相关联,并且对于跨组协作来说是“真”)。
  • @LorenaNicole 因为你还没有展示你的整个班级我不确定 self.is_private 是在哪里定义的,但似乎是当客户没有设置时,所以可以被排除在外。在我看来,问题的根源在于 is_private 为 False 但未设置客户。如果您想在 SQL 中确认,您应该查看组表而不是我认为的客户表。
猜你喜欢
  • 1970-01-01
  • 2022-01-10
  • 1970-01-01
  • 1970-01-01
  • 2013-07-27
  • 1970-01-01
  • 1970-01-01
  • 2018-02-23
  • 2016-11-17
相关资源
最近更新 更多