2014-02-10 40 views
1

我有这样一个模型:如何根据Tastypie中的孩子的孩子字段进行过滤?

Shop 
    Categories 
     Items 

我可以过滤店的类别是这样的:

categories = fields.ToManyField('api.CategoryResource', attribute=lambda bundle: Category.objects.filter(parent__isnull=True), full= True) 

比方说,我想,当我查询店铺来过滤发布的项目。

我该如何过滤?我应该在哪里写查询?

items = fields.ToManyField(ItemResource, attribute=lambda bundle: Item.objects.filter(category=bundle.obj, published=True),related_name='items', full=True) 

这个代码给我错误:

{"error": "The model '<Category: category1>' has an empty attribute '<function <lambda> at 0x10ba506e0>' and doesn't allow a null value."} 

回答

0

原来,当由拉姆达函数返回的列表为空,出现此错误。 因此,添加null = True将解决此问题。

所以,你最终这个:

items = fields.ToManyField(ItemResource, attribute=lambda bundle: Item.objects.filter(category=bundle.obj, published=True),related_name='items', full=True, null=True)