Django 如何根据子项进行筛选';Tastypie中的子字段?
我有一个这样的模型:Django 如何根据子项进行筛选';Tastypie中的子字段?,django,tastypie,Django,Tastypie,我有一个这样的模型: Shop Categories Items 我可以像这样过滤商店的类别: categories = fields.ToManyField('api.CategoryResource', attribute=lambda bundle: Category.objects.filter(parent__isnull=True), full= True) 假设我想在查询商店时筛选已发布的项目 我如何过滤?我应该在哪里写查询 items = f
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."}
{“error”:“模型“”具有空属性“”,不允许空值。”}
当lambda函数返回的列表为空时,会发生此错误。
因此,添加null=True将解决此问题
所以你最终会得到这样的结果:
items = fields.ToManyField(ItemResource, attribute=lambda bundle: Item.objects.filter(category=bundle.obj, published=True),related_name='items', full=True, null=True)