I figured out how to write client api for the GET POST PUT and DELETE
verbs for simple models with no relationship to an other model. I am
struggling to do figure out a POST for a resource with a foreign key.
Models (abbridged)
class Contact(models.Model):
....
class Test(models.Model):
name = models.CharField(max_length=30)
engineer = models.ForeignKey(Contact)
class TestResult(models.Model):
test = models.ForeignKey(Test)
comment = models.TextField()
duration = models.IntegerField()
runat = models.DateTimeField()
result = models.CharField(max_length=7, choices=result_choices)
Resources
class TestResource(ModelResource):
enginneer = fields.ForeignKey(ContactResource, 'enginneer')
class Meta:
queryset = Test.objects.all()
resource_name = 'test'
authorization= Authorization()
allowed_methods = ['get']
class TestResultResource(ModelResource):
test = fields.ForeignKey(TestResource, 'test')
class Meta:
queryset = TestResult.objects.all()
resource_name = 'testresult'
authorization= Authorization()
allowed_methods = ['get', 'post']
urls:
contact_resource = ContactResource()
test_resource = TestResource()
testresult_resource = TestResultResource()
urlpatterns = patterns(''
url(r'^api/', include(test_resource.urls)),
url(r'^api/', include(testresult_resource.urls)),
)
class TestResultClient:
def __init__(self, server, port):
self.address = '{0}:{1}'.format(server, port)
self.http = httplib2.Http()
def get(self, testresult_id):
url = 'http://{0}/api/testresult/{1}/'.format(self.address,
testresult_id)
return self.http.request(url)
def create(self, data):
url = 'http://{0}/api/testresult/'.format(self.address)
headers = {'Content-type': 'application/json'}
data = json.dumps(data)
return self.http.request(url, 'POST', headers=headers,
body=data)
def create(client):
now = datetime.datetime.now()
runat = datetime.datetime(now.year, now.month, now.day, now.hour,
now.minute, now.second)
testresult = {
"
test.id": "2",
"result": "Fatal",
"comment": "Http Server error",
"duration": 600,
"runat": str(runat),
}
status, content = client.create(testresult)
print('{0}: status {1}'.format('POST', status['status']))
print content
All my attempts at creating a TestResult fail. I do not know how the
foreign key is specified.
Is it
1) "testresult.test_id": "2"?
2) "
testresult.test.id": "2"?
3) "
test.id": "2"?
4) "test": "/api/test/2/"?
None work. Any help is appreciated :)
Thanks