我正在使用 Django 和tastepie 开发一个REST API,主键是来自django_extensions 的UUIDField。但是,将主键设置为 UUID 并不能很好地与 sweetpie 一起使用:当我使用 POST 创建资源时,它返回的 URI 是一个 int,而不是 UUID,并且提供的 URI 然后不可用,因为 API 的其余部分期望访问资源的 UUID。
我认为这是因为 UUIDField 仅替换了 Django pre_save 中 UUIDField 中的值,并且在此之前,tastepie 正在返回标头。
我尝试为 LocationResource 编写自定义 get_resource_uri,但传递给函数的对象还没有 UUID(只是正常的自动递增整数主键)。
我怎样才能让美味派返回资源的正确 UUID?有没有更好的方法让 pk 成为美味派会更喜欢的 UUID?
该模型:
from django.db import models
from django_extensions.db.fields import UUIDField
class Location(models.Model):
""" Stores information about a location. """
id = UUIDField(primary_key=True)
path = models.TextField()
def __unicode__(self):
return "{uuid}: {path}".format(uuid=self.id, path=self.path)
美味派模型资源(我仍在本地开发,因此尚未正确设置身份验证和授权):
class LocationResource(ModelResource):
class Meta:
queryset = Location.objects.all()
authentication = Authentication()
authorization = Authorization()
我所看到的(为便于阅读而格式化的 JSON):
$ curl --dump-header - -H "Content-Type: application/json" -X POST --data '{"path": "/path/to/directory/"}' http://localhost:8000/api/v1/location/
HTTP/1.0 201 CREATED
Date: Tue, 11 Jun 2013 19:59:07 GMT
Server: WSGIServer/0.1 Python/2.7.3
Vary: Accept
X-Frame-Options: SAMEORIGIN
Content-Type: text/html; charset=utf-8
Location: http://localhost:8000/api/v1/location/1/
$ curl --dump-header - -H "Content-Type: application/json" -X GET http://localhost:8000/api/v1/location/1/
HTTP/1.0 404 NOT FOUND
Date: Tue, 11 Jun 2013 19:59:27 GMT
Server: WSGIServer/0.1 Python/2.7.3
Vary: Accept
X-Frame-Options: SAMEORIGIN
Content-Type: text/html; charset=utf-8
$ curl --dump-header - -H "Content-Type: application/json" -X GET http://localhost:8000/api/v1/location/
HTTP/1.0 200 OK
Date: Tue, 11 Jun 2013 19:59:32 GMT
Server: WSGIServer/0.1 Python/2.7.3
Vary: Accept
X-Frame-Options: SAMEORIGIN
Content-Type: application/json
Cache-Control: no-cache
{"meta":
{"limit": 20, "next": null, "offset": 0, "previous": null, "total_count": 1},
"objects": [
{"id": "5fe23dd4-d2d1-11e2-8566-94de802aa978",
"path": "/path/to/directory/",
"resource_uri": "/api/v1/location/5fe23dd4-d2d1-11e2-8566-94de802aa978/"
}
]
}