我是Django的新手,我正在尝试使用tastypie来创建一个简单的API。我似乎无法找出在另一个资源中显示相关信息的正确方法。
Models.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()
数据库中的记录如下所示:
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
当我点击交易网址时,我看到以下内容 [{“id”:1,“bucket_name”:null,“date”:2013-03-31,“amount”:8.75,“account”:1},{...]
如何获取tastypie在存储桶表中执行查找以获取“名称”并返回JSON响应?
由于
答案 0 :(得分:0)
ToOneField将显示整个BucketResource对象,而不仅仅是其名称。它显示为null,因为您将属性param指定为'name',而它应该是TTransaction模型中指向TBucket模型的字段。在您的情况下,它将遵循:
bucket = fields.ToOneField(BucketResource, 'bucket', null=True)
但正如我所说它会向你展示整个BucketResource。如果您只需要来自TBucket模型的名称,您可以覆盖脱水方法:
def dehydrate(self, bundle):
bundle.data['bucket_name'] = bundle.obj.bucket.name
它只会以这种方式显示bucket_name