1

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 ?

3 Answers3

2

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(...)
David Wolever
  • 148,955
  • 89
  • 346
  • 502
1

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()
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • Really? How does the classmethod on the handler get called? I haven't noticed any reference to that in the documentation… But, then, undocumented features don't really surprise me :( – David Wolever Jun 16 '10 at 14:07
0

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.

lumingjing
  • 390
  • 2
  • 10