【问题标题】:django tastypie dehydrate from reverse relationdjango sweetpie 从反向关系中脱水
【发布时间】:2012-11-17 04:17:47
【问题描述】:

假设我有:

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

【问题讨论】:

    标签: django tastypie


    【解决方案1】:

    我要回答我自己的问题,我们需要在PersonResource 上添加这个:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-27
      • 2018-07-05
      • 2010-11-03
      • 2013-10-20
      • 2012-12-25
      • 1970-01-01
      相关资源
      最近更新 更多