我是 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 响应中返回?
谢谢