Tastypie, filtering many to many relationships

一个人想着一个人 提交于 2019-12-03 07:42:16

You can filter fields using lambda bundle attribute showing table name and field name.

tags = fields.ToManyField('django_app.api.TagsResource', attribute=lambda bundle: bundle.obj.tags.filter(tags__deleted=0))

Wow... I've been looking all day for this! the "attribute" is exactly what I was looking for. I almost started hacking at my models to do the filtering there out of despair.

From the Resource Field documentation for ToManyField:

Provides access to related data via a join table.

This subclass requires Django’s ORM layer to work properly.

This field also has special behavior when dealing with attribute in that it can take a callable. For instance, if you need to filter the reverse relation, you can do something like:

subjects = fields.ToManyField(SubjectResource, attribute=lambda bundle: Subject.objects.filter(notes=bundle.obj, name__startswith='Personal'))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!