tastypie:序列项0:期望的字符串,找到的函数

时间:2016-09-20 20:59:59

标签: python django tastypie

class ActionResource(ModelResource):
    #place = fields.ManyToManyField('restaurant.resource.PlaceResource', 'place', full=True, null=True)
    place = fields.ManyToManyField(PlaceResource,
                                attribute=lambda bundle: PlaceInfo.objects.filter(action=bundle.obj))

    class Meta:
        queryset = ActionInfo.objects.all()
        resource_name = 'action'

        filtering = {
            'place' : ALL_WITH_RELATIONS,
        }

class PlaceResource(ModelResource):
    location = fields.ManyToManyField(PlaceLocationResource, 'location')
    class Meta:
        queryset = PlaceInfo.objects.all()
        resource_name = 'place'

        filtering = {
            'id' : ALL,
        }

这是我的resource.py。使用此代码,我想过滤一些带有ID的地方:

http://localhost/api/v1/action/?place__id=2&format=json

通过行动ID,我只能找到一个地方,行动是唯一的地方。有了这个网址我得到错误:

sequence item 0: expected string, function found

Django模型看起来像PlaceModel有ManyToMany字段,引用ActionModel

http://localhost/api/v1/action/2/?format=json

给我正常的json参考地方

其他

我的Django模特:

class ActionInfo(models.Model):
    name        = models.ForeignKey(ActionName,     related_name="title",    on_delete=models.CASCADE, null=True, blank=True)

class PlaceInfo(models.Model):
    name            = models.ForeignKey(PlaceName, related_name="title", on_delete=models

.CASCADE,null = True)         action = models.ManyToManyField(ActionInfo,related_name =" action",blank = True)

我非常喜欢我必须这样构建我的资源:

class ActionResource(ModelResource):
    place   = fields.ToOneField(PlaceResource, 'place')

class PlaceResource(ModelResource):
    location    = fields.ManyToManyField(PlaceLocationResource, 
    action = fields.ToManyField('menus.resources.ActionResource', 'action', full=True)

但是我得到了这样的代码:

error: "The model '<ActionInfo: name>' has an empty attribute 'place' and doesn't allow a null value."

解决:

class ActionResource(ModelResource):
    place   = fields.ToManyField(PlaceResource, 'action', null=True)

现在它适用于:

http://localhost/api/v1/action/?place=1&format=json

1 个答案:

答案 0 :(得分:0)

尝试将ActionResource.place.attribute设置为等于该关系的名称(或反向名称,具体取决于您的型号)。

class ActionResource(ModelResource):
    place = fields.ToOneField(PlaceResource, 'reverse_name_here')