DoesNotExist: 客户匹配查询不存在(Django)

0 投票
1 回答
2893 浏览
提问于 2025-04-18 15:23

在我的Django应用中,我遇到了一个错误:“DoesNotExist: Customer matching query does not exist”。这个错误的堆栈跟踪显示,当我试图从一个组的客户信息中查询数据时,系统提示“资源不存在”,但实际上这个客户在数据库中是存在的(并且有我请求的信息):

 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文档,这个错误的描述是这样的:“注意,使用get()和使用filter()加上切片[0]是有区别的。如果没有结果匹配查询,get()会引发一个DoesNotExist异常。这个异常是查询所针对的模型类的一个属性——所以在上面的代码中,如果没有主键为1的Entry对象,Django会引发Entry.DoesNotExist。”

如果信息确实存在,但仍然出现上述错误,这可能是什么原因呢?

1 个回答

0

我不太明白你想要达到什么目的,不过其实你不需要去找 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}

撰写回答