0

我的 Django 项目中的两个模型是

class ContractPlans(models.Model):
  cp_id = models.CharField(primary_key = True, db_column = "ContractPlanId", max_length = 100L)
  parentorg = models.ForeignKey("Parentorgs")
  contractnum = models.ForeignKey("Contracts", db_column = "ContractNum")
  plan_id = models.CharField(max_length = 100L, db_column = "PlanID")
  eff_date = models.DateField()
  exp_date = models.DateField(null=True, blank=True)
  planname = models.CharField(max_length=100L, db_column='PlanName') 


class ContractPlanTags(models.Model):
  contract_plan_id = models.IntegerField(primary_key = True, db_column = "table_id")
  parentorg = models.ForeignKey("Parentorgs", db_column = "parentorg_id")
  contractnum = models.ForeignKey("Contracts", db_column = "ContractNum")
  planid = models.ForeignKey("ContractPlans", db_column = "PlanId")
  tag_id = models.IntegerField()
  tag_value_id = models.ForeignKey("Tags", db_column = "tag_value_id")
  eff_date = models.DateField()
  exp_date = models.DateField(null=True, blank=True)

我正在执行一个prefetch_related()查询ContractPlanTags

lst = ContractPlanTags.objects.prefetch_related().filter(parentorg = request.REQUEST["parentorg"])

这是为了在一次数据库命中中获取与该模型类关联的所有外键对象。

我的问题是 Django 不断抛出错误

DoesNotExist: ContractPlans matching query does not exist. 
Lookup parameters were {'cp_id__exact': u'805'}

我想要做的是将与序列化程序循环关联ContractPlans.plan_idContractPlans.planname在其中的值作为 JSON 对象传递给视图。

如何解决此错误?

4

2 回答 2

0

当您过滤 a 时foreign key,您需要传递该外部模型的对象:

parent_org = get_object_or_404(Parentorgs, pk=request.REQUEST["parentorg"])
lst = ContractPlanTags.objects.prefetch_related().filter(parentorg = parent_org)
于 2013-06-20T21:40:04.103 回答
0

错误告诉你出了什么问题:

DoesNotExist: ContractPlans matching query does not exist. 
Lookup parameters were {'cp_id__exact': u'805'}

您的一个ContractPlanTags对象具有无效的外键。您需要通过将密钥设置为或使用805None创建缺少的ContractPlans对象来解决此问题。cp_id

您还应该正确地强制执行您的数据库完整性,以防止它在将来发生。

于 2013-06-21T01:08:03.187 回答