django tastypie从反向关系中脱水

时间:2012-11-17 04:17:48

标签: django tastypie

假设我有:

models.py:

class Person(models.Model):
    user = models.OneToOneField(User)

    def get_album(self):
        return self.album_set.all()

class Album(models.Model):
    user = models.ForeignKey(Person)
    photo = models.ImageField(upload_to = 'blahblah')

api.py:

class PersonResource(ModelResource):

    class Meta:
        queryset = Person.objects.all()

class AlbumResource(ModelResource):

    class Meta:
        queryset = Album.objects.all()

如何使PersonResource上的字段脱水,使其值为.get_album()

我试图像这样使用ToManyField:

albums = fields.ToManyField(readonly = True)

但它抛出:

Exception Type: TypeError
Exception Value:    
__init__() takes at least 3 arguments (2 given)
Exception Location: C:\PHOTOBLOG\photoblog\person\api.py in PersonResource, line 8

1 个答案:

答案 0 :(得分:1)

我将回答我自己的问题,我们需要的是在PersonResource上添加:{/ p>

albums = fields.ToManyField('myapp.api.AlbumResource', 'album_set', full = True)

无需定义自定义方法或脱水。