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

2019-06-03 15:42发布

问题:

I have a model with ManyToManyField to another model. I would like to get all the info on a particular record (including the related info from other models) return by JSON.

How to get django-piston to display those values? I would be happy with just primary keys. Or can you suggest another option ?

回答1:

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


回答2:

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


回答3:

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.