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)
我解決它以這樣的方式,但我希望得到不重複
對不起,這是代碼的一部分,我更新了我的問題 –