如何在Tastypie中加载外键元素 [英] How to load the foreign keys elements in Tastypie
问题描述
在我的Django模型中,我有10个字段,有3个字段是外键。
在从GET请求中收到的JSON数据中,我得到所有的字段,而不是外键。
In my Django model, I have 10 fields and there are 3 fields which are foreign keys. In my JSON data which is received from a GET request, I am getting all the fields but not the foreign keys.
我也做了这个,但是我还没有在JSON数据中获取这些字段:
I have also done this, but I am still not getting those fields in the JSON data:
DataFields = MyData._meta.get_all_field_names()
class MyResource(ModelResource):
class Meta:
queryset = MyData.objects.all()
resource_name = 'Myres'
serializer = Serializer(formats=['json'])
filtering = dict(zip(DataFields, [ALL_WITH_RELATIONS for f in DataFields]))
例如,我在模型中有如 city
的字段,但该字段在我从中得到的JSON中是不可用的。
For example, I have the field in model like city
, but that field is not available in the JSON I get from it.
有没有办法在JSON中可以自动获得 city:city__name
Is there any way that in JSON I can get city:city__name
automatically?
如果我这个,然后我得到城市,但是我可以不做定义:
If I do this, then I get the city, but can I do that without defining:
def dehydrate(self, bundle):
bundle.data["city_name"] = bundle.obj.city__name
return bundle
推荐答案
您将要创建相关资源用于您的外键字段,并将其嵌入到 MyResource
中。如果您使嵌入式资源 full = True
,则在获取 MyResource
时会脱水,否则将嵌入它作为相关资源uri。
You'll want to create related resources for your foreign key fields and embed them in MyResource
. If you make the embedded resource full=True
, it'll dehydrate it when fetching MyResource
, otherwise it'll embed it as the related resource uri.
class RelatedResource(ModelResource):
class Meta:
...
class MyResource(ModelResource):
related = fields.ForeignKey(RelatedResource, full=True)
class Meta:
...
然后可以通过过滤?related__field = value
在GET请求中 MyResource
。
You can then filter by ?related__field=value
in the GET request to MyResource
.
如果您只想要模型的 __ unicode __
返回的字段,则可以尝试执行以下操作(而不是嵌入相关资源):
If you're just wanting the field returned by the model's __unicode__
, you can try doing the following (rather than embedding a related resource):
class MyResource(ModelResource):
city = fields.CharField(attribute="city")
class Meta:
...
其中city是t的字段名称他的外键是 MyData
模型。
Where "city" is the field name of the foreign key on the MyData
model.
这篇关于如何在Tastypie中加载外键元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!