0

我是 Django 新手,我正在尝试使用 sweetpie 创建一个简单的 API。我似乎无法弄清楚在一个资源中从另一个资源中显示相关信息的正确方法。

模型.py

class TBucket(models.Model):
    name = models.CharField(max_length=50)
    bucket_type = models.IntegerField()
    bucket_seed = models.DecimalField(null=True, max_digits=10, decimal_places=2)
    class Meta:
        db_table = u't_bucket'
        ordering = ['name']

class TTransaction(models.Model):
    bucket = models.ForeignKey(Tbucket)
    date = models.DateTimeField()
    amount = models.DecimalField(null=True, max_digits=10, decimal_places=2)
    account = models.IntegerField()

api.py(片段)

class BucketResource(ModelResource): 
    class Meta:
        queryset = TBucket.objects.all()
        resource_name = 'bucket'
        include_resource_uri = False
        allowed_methods = ['get','post','put','delete']
        authorization = Authorization()

class TransactionResource(ModelResource):
    bucket_name = fields.ToOneField(BucketResource, 'name', null=True)

    class Meta:
        queryset = TTransaction.objects.all()
        resource_name = 'transaction'
        include_resource_uri = False
        allowed_methods = ['get','post','put','delete']
        authorization= Authorization()

DB 中的记录如下所示:

t_bucket
id:1, name:Food, bucket_type:1, bucket_seed:50.00
id:2, name:Gas, bucket_type:1, bucket_seed:25.00

t_transaction:
id:5, bucket_id:1, date:2013-03-31, amount:8.75, account:1
id:6, bucket_id:2, date:2013-04-01, amount:25.50, account:1

当我点击交易 URL 时,我看到以下 [{"id": 1, "bucket_name":null, "date":2013-03-31, "amount":8.75, "account":1},{。 ..]

我怎样才能让美味派在存储桶表中进行查找以获取“名称”并在 JSON 响应中返回?

谢谢

4

1 回答 1

0

ToOneField 将显示整个 BucketResource 对象,而不仅仅是它的名称。它向您显示 null 因为您将属性参数指定为“名称”,而它应该是 TTransaction 模型中指向 TBucket 模型的字段。在您的情况下,它将如下:

bucket = fields.ToOneField(BucketResource, 'bucket', null=True)

但正如我所说,它将向您展示整个 BucketResource。如果您只需要 TBucket 模型中的名称,则可以覆盖 dehydrate 方法:

def dehydrate(self, bundle):
    bundle.data['bucket_name'] = bundle.obj.bucket.name

它只会以这种方式向您显示 bucket_name

于 2013-05-06T10:55:19.497 回答