我有这个模型:
# models.py
from django.contrib.auth.models import User
class Test(models.Model):
author = models.ForeignKey(User, related_name="tests")
title = models.CharField(_("title"), max_length=100)
然后在
api
django 活塞网络服务的文件夹:class TestHandler(BaseHandler):
allowed_methods = ("GET")
model = Test
fields = ("title", ("author", ("username",)))
def read(self, request, id):
base = self.model.objects
try:
r = base.get(pk=id)
return r
except:
return rc.NOT_FOUND
如果我调用这个网络服务,那么我得到:
{
"title": "A test"
"author": {
"username": "menda",
"first_name": "",
"last_name": "",
"is_active": true,
"is_superuser": true,
"is_staff": true,
"last_login": "2011-02-09 10:39:02",
"password": "sha1$83f15$feb85449bdae1a55f3ad5b41a601dbdb35c844b7",
"email": "b@a.as",
"date_joined": "2011-02-02 10:49:48"
},
}
我也试过使用
exclude
,但它也不起作用。如何只获取
author
的用户名?谢谢!
最佳答案
好的,所以问题在于 Piston 使用的是另一个 Handler 类在 User 模型上定义的字段集,而不是此处指定的嵌套字段。
另一位用户在此处引用了活塞讨论组中完全相同的问题:
http://groups.google.com/group/django-piston/browse_thread/thread/295de704615ee9bd
该问题显然是由 Piston 的序列化代码中的错误引起的。
用文档的话来说:
By using a model in a handler, Piston will remember your fields/exclude directives and use them in other handlers who return objects of that type (unless overridden.)
这一切都很好,除了“(除非被覆盖。)”的情况似乎没有得到正确处理。
我认为对emitters.py 稍作修改可能会解决这个问题(第160-193 行)...
if handler:
fields = getattr(handler, 'fields')
if not fields or hasattr(handler, 'fields'):
...dostuff...
else:
get_fields = set(fields)
哪个应该(也许?)读
if fields:
get_fields = set(fields)
else:
if handler:
fields = getattr(handler, 'fields')
...dostuff...
如果您决定尝试修补emitters.py,请告诉我这是否有效 - 在 django-piston 中修补它会很好。
干杯!
关于django - 无法在活塞中排除用户的外键字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4943911/