更改Django对象查询的查找参数

时间:2013-06-20 21:35:08

标签: python django django-models

我的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对象传递给视图。

如何解决此错误?

2 个答案:

答案 0 :(得分:0)

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

parent_org = get_object_or_404(Parentorgs, pk=request.REQUEST["parentorg"])
lst = ContractPlanTags.objects.prefetch_related().filter(parentorg = parent_org)

答案 1 :(得分:0)

错误告诉你错误:

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

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

您还应该正确地强制执行数据库完整性,以防止将来发生这种情况。