python django-tastypie 对象创建未正确返回数据
我设置了一个简单的API和资源,连接到一个已经存在的数据库(所以我需要在模型中指定表名和列名)。我可以正常创建和列出对象。但是当我创建一个对象时,Location头部信息总是无法正确返回,也无法返回创建的数据。
创建一个对象的代码:
curl --dump-header - -H "Content-Type: application/json" -X POST --data '{"system_key": "test","system_nam": "test","system_url": "https://test/test"}' http://127.0.0.1:7000/api/system/?ticket=TGT-585-d9f9effb36697401dce5efd7fc5b3de4
响应结果:
HTTP/1.0 201 CREATED
Date: Thu, 14 Feb 2013 18:58:17 GMT
Server: WSGIServer/0.1 Python/2.7.3
Vary: Accept
Content-Type: text/html; charset=utf-8
Location: http://127.0.0.1:7000/api/system/None/
注意Location头部信息。看起来对象是成功创建的,但信息没有从数据库返回到API,所以无法在响应中使用。为了清楚起见,数据库表中的数据是正确的。
如果我添加了 always_return_data = True
,我得到的结果是:
HTTP/1.0 400 BAD REQUEST
Date: Thu, 14 Feb 2013 19:00:32 GMT
Server: WSGIServer/0.1 Python/2.7.3
Content-Type: application/json
{"error": "The object '<system: MRMteste>' has an empty attribute 'system' and doesn't allow a default or null value."}
我的资源和模型非常简单:
资源的代码:
class SystemResource(ModelResource):
class Meta:
list_allowed_methods = ['get', 'post']
detail_allowed_methods = ['get', 'put','patch']
queryset = system.objects.all()
resource_name = 'system'
authorization = Authorization()
authentication = customAuth.CustomAuthentication()
def hydrate_system_timestamp(self, bundle):
bundle.data['system_timestamp'] = get_now_time()
return bundle
模型的代码:
class system(models.Model):
list_display = ('system_nam')
system = models.IntegerField(primary_key=True, db_column="system_id")
system_nam = models.CharField(max_length=50)
system_key = models.CharField(max_length=255)
system_url = models.CharField(max_length=100)
is_deleted_flg = models.BooleanField()
system_timestamp = models.DateTimeField(default=datetime.now)
def __unicode__(self):
return self.system_nam
class Meta:
db_table = "system"
文档中没有关于这个问题的说明。有没有人能告诉我,使用tastypie时我的模型和资源是否正确?我使用的是截至目前最新版本的tastypie和django。
非常感谢!
2 个回答
1
你需要在资源的元类中进行设置:
always_return_data = True
并且尽量把你的唯一标识字段命名为默认的名字“id”,而不是“service”。
1
其实我已经解决了这个问题。
在模型中,如果你需要定义列名,就像我做的那样,不要在主键上使用IntegerField。应该这样做:
system = models.AutoField(primary_key=True, db_column="system_id")
tastypie在处理新创建的对象时,需要在模型上定义自增,这样它才能知道最后创建的ID是什么。发现这个问题真不错,希望将来能帮助到某个人。