Search code examples
djangodjango-modelsforeign-key-relationshiptastypie

Django | Tastypie: Create record with ForeignKey__id


class D(BaseRsrc):
    a1 = fields.ForeignKey(D1Resource, 'a1', full=True, blank=True)
    a2 = fields.ForeignKey(D2Resource, 'a2', full=True, blank=True)
    a3 = fields.ForeignKey(D3Resource, 'a3', full=True, blank=True)
    class Meta(BaseRsrc.Meta):
        resource_name = 'sample_endpoint'
        queryset = M.objects.all()
        include_resource_uri = True

The POST request I send is:

{"data":
    {"a1_id":110,"a2_id":10802,"a3_id":"10804"}
}

I get the error

{
 "D": 
    { 
      "a1": ["This field cannot be null."], 
      "a2": ["This field cannot be null."], 
      "a3": ["This field cannot be null."]}
}

Is there a tastypie way of doing this correctly? The Database expects just the foreign key ids. Which is what I am sending. Do I need to override the hydrate for each? This sounds inefficient.


Solution

  • Don't let database mislead you. Tastypie lays directly on the Django's ORM.

    So think of your foreign key as an object instead of just id column. You should use resource representation path instead:

    {"a1": "/path/to/a1resource/110", "a2": "/path/to/a2resource/10802", "a3": "/path/to/a3resource/10804"}
    

    You simply use resource uri representation in tastypie's foregin keys.