【发布时间】:2013-06-07 19:51:07
【问题描述】:
我正在使用 Django 和 sweetpie 开发一个 REST API,主键是来自 django_extensions 的 UUIDField。但是,将主键设置为 UUID 并不能很好地与美味派一起使用:当我使用 POST 创建资源时,它返回的 URI 是一个 int,而不是 UUID,并且提供的 URI 将不可用,因为 API 的其余部分期望用于访问资源的 UUID。
我认为这是因为 UUIDField 仅替换了 Django 的 pre_save 中 UUIDField 中的值,并且在此之前,tastepie 会返回标头。
我尝试为 LocationResource 编写自定义 get_resource_uri,但传递给函数的对象还没有 UUID(只是普通的自动递增整数主键)。
我怎样才能让 sweetpie 为资源返回正确的 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)
tastepie ModelResource(我仍在本地开发,因此尚未正确设置身份验证和授权):
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/"
}
]
}
【问题讨论】:
标签: django tastypie uuid django-extensions