django-piston: how to get values of a many to many field?

六月ゝ 毕业季﹏ 提交于 2019-12-07 07:41:25

I may be wrong, but this should do it:

class PersonHandler(BaseHandler):
    model = Person
    fields = ('id', ('friends', ('id', 'name')), 'name')

    def read(self, request):
        return Person.objects.filter(...)

You need to define a classmethod on the handler that returns the many-to-many data, I don't believe Piston does this automatically.

class MyHandler(BaseHandler):
    model = MyModel
    fields = ('myfield', 'mymanytomanyfield')

    @classmethod
    def mymanytomanyfield(cls, myinstance):
        return myinstance.mymanytomanyfield.all()

My code:

Models:

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)

Handle:

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(...)

Works petty good.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!