Tastypie - 链接到“ForeignKey”

时间:2013-05-14 14:49:56

标签: django django-models tastypie

我有两个下面列出的传统型号。当libtype_id>时,Library.libtype_id 有效地是LibraryType的外键。 0.当我满足条件时,我想将此表示为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 个答案:

答案 0 :(得分:1)

应该不是

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

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

(没有'_id')

我相信,因为您正在向该字段递送int并且它正在尝试从中获取pk

<强>更新

错过libtype_idIntegerField,而不是ForeignKey(问题的全部内容)

我个人会向Library添加一个方法来检索LibraryType对象。这样您就可以访问LibraryType中的Library,并且不必覆盖任何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')