【问题标题】:Tastypie - Linking to a "ForeignKey"Tastypie - 链接到“外键”
【发布时间】:2013-05-14 14:49:56
【问题描述】:

我在下面列出了两个旧型号。当 libtype_id > 0 时,Library.libtype_id实际上是 LibraryType 的外键。当满足该条件时,我想将其表示为 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'",

【问题讨论】:

    标签: django django-models tastypie


    【解决方案1】:

    不应该

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

    成为

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

    (没有“_id”)

    我相信您正在向该字段发送int,并且它正试图从中获取pk

    更新

    错过了 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')
    

    【讨论】:

    • 这有点好.. 但现在我的 get_detail 有问题。我应该如何引用它 - 我想要 uri?
    • 我不太确定我明白你的意思。你需要dehydrate_libtype吗?
    • 它与特定资源 id 有什么关系?
    • fields.ForeignKey 会将 uri 返回到相关对象。如果你添加full=True 那么它将返回整个相关对象
    • 是的 - 但是当 libtype_id > 0 时,是什么将 libtype_id 链接到该外键?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-19
    • 1970-01-01
    • 2023-03-06
    • 2011-12-02
    • 2012-08-08
    • 1970-01-01
    相关资源
    最近更新 更多