Tastypie'Search'仅返回资源名称

时间:2013-12-30 22:32:05

标签: python django api tastypie

我正在尝试创建一个通过ForeingKey字段(或者更确切地说是字段中引用的对象)来过滤对象的函数。我编写了下面包含的功能,它基于Tastypie Cookbook的添加搜索功能。该函数的确有效,它返回对象,但它只返回对象的名称作为字符串。

这是调用函数的结果:

{'receipt_items': [<ReceiptItem: Item1>, <ReceiptItem: Item2>, <ReceiptItem: Item3>]}

这是我的资源:

class ReceiptItemResource(ModelResource):
receipt = fields.ToOneField(ReceiptResource, 'receipt', full = True)
class Meta:
    queryset = ReceiptItem.objects.all()
    serializer = Serializer()
    allowed_methods = ['get', 'post', 'put', 'delete']
    always_return_data = True

def prepend_urls(self):
    return [
        url(r'^(?P<resource_name>%s)/filter%s$' % (self._meta.resource_name, trailing_slash()), self.wrap_view('filter_by_receipt'), name = 'filter_by_receipt'),

        ]

def filter_by_receipt(self, request, **kwargs):
    data = self.deserialize(request, request.body, format = request.META.get('CONTENT_TYPE', 'application/json'))

    receipt_id = data.get('receipt_id', '')
    print receipt_id

    receipt = Receipt.objects.get(id = receipt_id)

    receipt_items = ReceiptItem.objects.filter(receipt = receipt)

    item_list = {
        'receipt_items' : receipt_items,
    }

    print item_list
    return self.create_response(request, receipt_items)

    #return super(ReceiptItemResource, self).get_object_list(request).filter(receipt = receipt)

def get_object_list(self, request):
    user = request.user
    member = user.member
    owner = member.owner


    return super(ReceiptItemResource, self).get_object_list(request).filter(owner = owner)

理想情况下,我希望此函数返回JSON中的完整对象详细信息。有没有办法让这种情况发生?

我已经研究过Tastypie的资源过滤,但我不相信这会起作用,因为我试图过滤的字段是ForeignKey。

非常感谢所有帮助,谢谢。

1 个答案:

答案 0 :(得分:0)

你不应该这样做。您可以使用过滤选项

默认过滤foreignKey
from tastypie.resources import ALL, ALL_WITH_RELATIONS

class RecieptResource(ModelResource):
    class Meta: 
       fields = ["id"]
       filtering = {
         "id": ALL
       }

class ReceiptItemResource(ModelResource):
    receipt = fields.ToOneField(ReceiptResource, 'receipt', full = True)
    class Meta:
        queryset = ReceiptItem.objects.all()
        allowed_methods = ['get', 'post', 'put', 'delete']
        always_return_data = True
        filtering = {
            "reciept": ALL_WITH_RELATIONS
        }

现在,以下内容应该是url(取决于你如何配置你的内容)应该给你你想要的东西

/ API / V1 /收据项/ receipt__id = 1&安培;格式= JSON