2012-11-17 93 views
1

假設我有: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

我要回答我的問題,我們需要的是添加這個上PersonResource

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

無需定義自定義方法或脫水。