0

我在下面列出了两个旧模型。当libtype_id > 0 时,Library.libtype_id实际上是 LibraryType 的外键。当满足该条件时,我想将其表示为 TastyPie 中的 ForeignKey 资源。

有人可以帮我吗?我见过这个,但我不确定这是同一件事吗?非常感谢!!

# 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'",
4

1 回答 1

1

不应该

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

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

(没有'_id')

我相信你正在处理这个领域,int并且它正试图从中获得pk

更新

错过的libtype_id是一个IntegerField,而不是一个ForeignKey(问题的重点)

就我个人而言,我会添加一个方法Library来检索LibraryType对象。这样您就可以访问LibraryTypefrom theLibrary并且您不必重写任何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')
于 2013-05-14T15:01:49.377 回答