我有一个模型,用ManyToManyField连接到另一个模型。我想得到所有的信息,在一个特定的记录(包括从其他型号的相关信息)返回的JSON。
如何让django-piston显示这些值?我只需要主键就可以了。或者你能推荐另一个选择吗?
发布于 2010-06-16 06:48:14
我可能错了,但这应该可以做到:
class PersonHandler(BaseHandler):
model = Person
fields = ('id', ('friends', ('id', 'name')), 'name')
def read(self, request):
return Person.objects.filter(...)发布于 2010-06-16 14:30:13
你需要在处理程序上定义一个类方法来返回多对多数据,我不相信Piston会自动做到这一点。
class MyHandler(BaseHandler):
model = MyModel
fields = ('myfield', 'mymanytomanyfield')
@classmethod
def mymanytomanyfield(cls, myinstance):
return myinstance.mymanytomanyfield.all()发布于 2013-01-02 21:31:51
我的代码:
型号:
class Tag(models.Model):
"""docstring for Tags"""
tag_name = models.CharField(max_length=20, blank=True)
create_time = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return self.tag_name
class Author(models.Model):
"""docstring for Author"""
name = models.CharField(max_length=30)
email = models.EmailField(blank=True)
website = models.URLField(blank=True)
def __unicode__(self):
return u'%s' % (self.name)
class Blog(models.Model):
"""docstring for Blogs"""
caption = models.CharField(max_length=50)
author = models.ForeignKey(Author)
tags = models.ManyToManyField(Tag, blank=True)
content = models.TextField()
publish_time = models.DateTimeField(auto_now_add=True)
update_time = models.DateTimeField(auto_now=True)
def __unicode__(self):
return u'%s %s %s' % (self.caption, self.author, self.publish_time)句柄:
class BlogAndTagsHandler(BaseHandler):
allowed_methods = ('GET',)
model = Blog
fields = ('id' 'caption', 'author',('tags',('id', 'tag_name')), 'content', 'publish_time', 'update_time')
def read(self, request, _id=None):
"""
Returns a single post if `blogpost_id` is given,
otherwise a subset.
"""
base = Blog.objects
if _id:
return base.get(id=_id)
else:
return base.all() # Or base.filter(...)效果很好。
https://stackoverflow.com/questions/3049519
复制相似问题