Tastypie:无法从相关资源中获取一个字段

时间:2016-10-12 22:38:00

标签: django django-queryset tastypie

问题在于ToManyField返回一组对象或一组网址。我如何从相关表中只获得一个字段?

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

我尝试使用'action'的querySet操作并添加'only'方法,但它不起作用('distinct'工作正常),它返回'action'的所有字段。也许有同样的方法'仅'恰好适合tastypie,但我没有看到。谢谢。

更新:

bundle.data['types']  = []
for i in bundle.obj.action.distinct('type'):
    bundle.data['types'].append(i.type)

我以这种方式解决了它,但我希望得到没有迭代的普通QuerySet

1 个答案:

答案 0 :(得分:0)

您应该创建一个属性并将该属性名称添加到字段列表中。