Search code examples
pythondjangotastypie

tastypie doesn't return id field


I have following resources:

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

When I do a GET request to RefSegmentResource, I get a list like this:

{
"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": ...
}, ...

Note the id field in response. But when I do a GET request to RefPredicateResource, I don't receive it as a field:

{
"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"
}, ...

How to configure the resource so that it returns primary key (id)?


Solution

  • I got it working finally. The problem was in RefPredicate model definition:

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

    I misunderstood the primary_key argument, meaning to say that segment column should point at primary key of TestSegment model. But Django understands this as "create segment_id column, which is a primary key (as long it is a one-to-one relation) and points at primary key of TestSegment".

    Thus, Tastypie saw a primary key which was segment instead of id, and returned it.