0
问题在于ToManyField返回一组对象或一组url。我如何才能从相关表中获得一个字段?Tastypie:无法从相关资源获取一个字段
class PlaceResource(ModelResource):
location = fields.ManyToManyField(PlaceLocationResource, 'location')
action = fields.ToManyField('menus.resources.ActionResource',
attribute= lambda bundle: bundle.obj.action.distinct('type').only('name'),
null=True, related_name='place', full=True)
class Meta:
queryset = PlaceInfo.objects.all()
resource_name = 'place'
filtering = {
'id' : ALL,
}
def dehydrate(self, bundle):
#raise sdf
bundle.data['type'] = bundle.obj.type.name
bundle.data['name'] = bundle.obj.name.name
bundle.data['close_time'] = bundle.obj.close_time
bundle.data['location'] = {}
bundle.data['location']['address'] = (bundle.obj.location.all()[0]).address
bundle.data['location']['latitude'] = (bundle.obj.location.all()[0]).latitude
bundle.data['location']['longtitude'] = (bundle.obj.location.all()[0]).longtitude
if bundle.obj.comments == None:
bundle.data['comments'] = 0
if bundle.obj.price == None:
bundle.data['price'] = 0
#if bundle.obj.rate_amount == None:
# bundle.data['rate_amount'] = 0
#if bundle.obj.rate_makr == None:
# bundle.data['rate_makr'] = 0
bundle.data['rate_amount'] = {
1 : 10,
2 : 15,
3 : 40,
4 : 35,
5 : 27
}
if bundle.obj.open_time == None:
bundle.data['open_time'] = 'Unsetted'
if bundle.obj.close_time == None:
bundle.data['close_time'] = 'Unsetted'
if bundle.obj.location == None:
bundle.data['location'] = 'Unsetted'
if bundle.obj.type == 'restaurant.PlaceType.None':
bundle.data['type'] = 'Unsetted'
#bundle.obj.action = bundle.obj.action.distinct('type').only('type')
#bundle.data['types'] = bundle.obj.action
return bundle
我试图与“行动”的queryset的操纵相加法“仅仅”,但它不工作(“不同” workes罚款),它返回“行动”的所有领域。也许有同样的方法'唯一'准确地为tastypie,但我没有看到。谢谢。
更新:
bundle.data['types'] = []
for i in bundle.obj.action.distinct('type'):
bundle.data['types'].append(i.type)
我解决它以这样的方式,但我希望得到不重复
对不起,这是代码的一部分,我更新了我的问题 –