2013-05-14 68 views
0

我有兩個舊的模型列在下面。 Library.libtype_id有效當libtype_id> 0時,一個外鍵給LibraryType。我想在滿足條件時將它表示爲TastyPie中的ForeignKey資源。Tastypie - 鏈接到「ForeignKey」

有人可以幫我嗎?我看過this,但我不確定它是一回事嗎?非常感謝!!

# models.py 
class LibraryType(models.Model): 
    id = models.AutoField(primary_key=True) 
    name = models.CharField(max_length=96) 

class Library(models.Model): 
    id = models.AutoField(primary_key=True) 
    name = models.CharField(max_length=255) 
    project = models.ForeignKey('project.Project', db_column='parent') 
    libtype_id = models.IntegerField(db_column='libTypeId') 

這裏是我的api.py

class LibraryTypeResource(ModelResource): 

    class Meta: 
     queryset = LibraryType.objects.all() 
     resource_name = 'library_type' 

class LibraryResource(ModelResource): 
    project = fields.ForeignKey(ProjectResource, 'project') 
    libtype = fields.ForeignKey(LibraryTypeResource, 'libtype_id') 

    class Meta: 
     queryset = Library.objects.all() 
     resource_name = 'library' 
     exclude = ['libtype_id'] 

    def dehydrate_libtype(self, bundle): 
     if getattr(bundle.obj, 'libtype_id', None) != 0: 
      return LibraryTypeResource.get_detail(id=bundle.obj.libtype_id) 

當我這樣做不過我發現了以下錯誤http://0.0.0.0:8001/api/v1/library/?format=json

"error_message": "'long' object has no attribute 'pk'", 

回答

1

不應該

libtype = fields.ForeignKey(LibraryTypeResource, 'libtype_id') 

libtype = fields.ForeignKey(LibraryTypeResource, 'libtype') 

(不「_id」)

我相信,這是你交給該領域的int,並試圖從中獲得pk

UPDATE

錯過了libtype_idIntegerField,不是ForeignKey(問題的整點)

個人而言,我想補充的方法對Library檢索LibraryType對象。通過這種方式,您可以從Library訪問LibraryType,並且不必覆蓋任何dehydrate方法。

class Library(models.Model): 
    # ... other fields 
    libtype_id = models.IntegerField(db_column='libTypeId') 

    def get_libtype(self): 
     return LibraryType.objects.get(id=self.libtype_id) 

class LibraryResource(ModelResource): 
    libtype = fields.ForeignKey(LibraryTypeResource, 'get_libtype') 
+0

這有點更好..但現在我有我的get_detail問題。我應該如何引用 - 我想要uri? – rh0dium 2013-05-14 15:46:42

+0

我不太清楚我是否有你。你需要'dehydrate_libtype'嗎? – rockingskier 2013-05-14 15:51:04

+0

它還與其他特定資源ID相關嗎? – rh0dium 2013-05-14 15:52:28