I have created a Django REST API using Django Rest Framework.
I use 3 different clients to hit this app:
- Curl (for debugging purposes)
- Swagger Interface (for debugging purposes)
- My Angular application
I have a perplexing problem that data returned by the API is being corrupted by Swagger and Angular but not by Curl.
My Django model looks like this:
class MyModel1(CachingMixin, models.Model):
id = models.BigIntegerField(default=make_id, primary_key=True)
name = models.CharField(max_length=50, null=False, blank=False,)
The make_id()
method referenced above is described here. I recently implemented this change from the standard Django assigned and auto-incremented primary key. As part of that change, I converted id from an IntegerField
to a BigIntegerField
.
I have some other Django view code (which I have not shown here) that creates an endpoint called GetMyModel1ByName
. That endpoint returns a serialized instance of MyModel1
. Here is the curl showing what happens when I hit that endpoint. It works perfectly:
$ curl http://localhost:4212/api/getMyModel1ByName/?name=my-name
{"id": 10150133855458395, "name": "my-name"}
Now here is what happens when I hit the same endpoint from Chrome's Developer console:
> $http = angular.element(document.body).injector().get('$http');
> $http.get("http://localhost:4212/api/getMyModel1ByName/?name=my-name").then(function(response) { console.log(JSON.stringify(response.data)) }).catch(function (error) { console.log(error.data) });
{"id":10150133855458396, "name":"my-name"}
As you can see curl reports the ID as 10150133855458395. That's correct. That's what is in the Database. However Angular reports it as 10150133855458396. The final digit is wrong. The difference is 1. It's very surprising!
This is a truly perplexing error. My Django code is so simple that I'm very confident that there is no mistake in it. Instead I feel that change the id
field from IntegerField
to BigIntegerField
might have caused this problem. Why is it happening and what is the solution?? It's ruining the functionality of my application. I'm seeing the same corruption when I hit this endpoint through Swagger.
EDIT: The other questioner is experiencing the same problem I am. It's great to know that I'm not the only one!! However, the answers on that question are not really answers. They don't explain the cause. And they don't tell me how I should solve the issue in my Angular JS code.