tastypie不返回id字段

时间:2013-12-10 11:03:23

标签: python django tastypie

我有以下资源:

class RefSegmentResource(ModelResource):
  class Meta(AuthMeta): # AuthMeta has only authorization + authentification
    queryset = TestSegment.objects.all()
    resource_name = 'refsegment'
    always_return_data = True


class RefPredicateResource(ModelResource):
  result = fields.ToOneField('hmeant.resources.SRLResultResource', 'result')
  token_indices = fields.CharField(attribute='token_indices')
  segment = fields.ToOneField('hmeant.resources.RefSegmentResource', 'segment')

  class Meta(AuthMeta):
    queryset = RefPredicate.objects.all()
    resource_name = 'refpredicate'
    always_return_data = True

当我向RefSegmentResource发出GET请求时,我得到一个这样的列表:

{
"meta": {
  "limit": 20,
  "next": "/api/demo/refsegment/?offset=20&limit=20&format=json",
  "offset": 0,
  "previous": null,
  "total_count": 100
},
"objects": [
{
  "id": 1,
  "resource_uri": "/api/demo/refsegment/1/",
  "text_origin": ...,
  "text_reference": ...
}, ...

请注意响应中的id字段。但是,当我向RefPredicateResource发出GET请求时,我不会将其作为字段接收:

{
"meta": {
  "limit": 20,
  "next": null,
  "offset": 0,
  "previous": null,
  "total_count": 2
},
"objects": [
{
    "resource_uri": "/api/demo/refpredicate/1/",
    "result": "/api/demo/iteration/1/",
    "segment": "/api/demo/refsegment/1/",
    "token_indices": "1,2,3"
}, ...

如何配置资源以便返回主键(id)?

1 个答案:

答案 0 :(得分:0)

我终于开始工作了。问题出在RefPredicate模型定义中:

class RefPredicate(Label):
   segment = models.OneToOneField(TestSegment, primary_key=True)

我误解了primary_key参数,意思是说segment列应该指向TestSegment模型的主键。但Django将此理解为“创建segment_id列,这是一个主键(只要它是一对一的关系)并指向TestSegment的主键”。

因此,Tastypie看到了一个segment而不是id的主键,并将其返回。