【问题标题】:Tastypie: can't get one field from related resourceTastypie:无法从相关资源中获取一个字段
【发布时间】:2016-10-12 22:37:59
【问题描述】:

问题在于 ToManyField 返回一组对象或一组 url。我怎样才能从相关表中只获取一个字段?

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'的所有字段。也许有同样的方法“只”完全适用于美味派,但我没有看到。谢谢。

更新:

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

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

【问题讨论】:

    标签: django django-queryset tastypie


    【解决方案1】:

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

    【讨论】:

    • 对不起,这是代码的一部分,我已经更新了我的问题
    猜你喜欢
    • 1970-01-01
    • 2019-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-04
    • 1970-01-01
    相关资源
    最近更新 更多