【问题标题】:tastypie display raw foreign key id valuesweetpie 显示原始外键 id 值
【发布时间】:2013-08-14 22:09:14
【问题描述】:

我正在尽我所能返回相关记录 ID 的值(外键引用)使用美味派。默认情况下,会从结果中过滤掉外键。

我有以下模型:

class Category(models.Model):
    """Finance category"""
    class Meta:
        db_table = 'category'
    parent = models.ForeignKey('self')
    name = models.CharField(max_length=32)
    TYPES = (
        ('outcome', 'outcome'),
        ('income', 'income'),
    )
    type = models.CharField(max_length=7,choices=TYPES)
    created_at = models.DateTimeField()
    updated_at = models.DateTimeField()
    created_by = models.ForeignKey(User, db_column='created_by', related_name='createdCategories')
    updated_by = models.ForeignKey(User, db_column='updated_by', related_name='updatedCategories')

我在这里有两个关系。 parent 是递归关系(它是一个类别树表)。 created_by 是与用户的关系。 API 正在返回以下值: * ID * 姓名 * created_at * 更新_at * 类型 * resource_uri

我可以做些什么来让tastepie返回父(_id)或created_by(或只是任何外键)?

以下是我从另一个操作系统问题中尝试过的:

class IncomeCategoryResource(ModelResource):
    parent_id = models.IntegerField(attribute="parent_id")
    class Meta:
        queryset = Category.objects.filter(type='income')

很遗憾,整个 API 都失败了:

__init__() got an unexpected keyword argument 'attribute'

我还尝试将attribute kwarg 替换为db_column。这个被忽略了。

请帮帮我:)

【问题讨论】:

    标签: django tastypie


    【解决方案1】:

    首先,IntegerField 有错误。您应该使用tastypie 的字段(tastypie.fields),而不是django 模型字段(django.db.models)。那么你的资源应该是这样的:

    class IncomeCategoryResource(ModelResource):
        parent_id = IntegerField(attribute="parent__id")
        class Meta:
            queryset = Category.objects.filter(type='income')
    

    注意使用双下划线来获取父级的 id 字段。

    【讨论】:

      猜你喜欢
      • 2019-12-07
      • 1970-01-01
      • 2019-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-14
      • 2017-02-14
      相关资源
      最近更新 更多