Skip to content Skip to sidebar Skip to footer

Tastypie, Filtering Many To Many Relationships

I have two models that are linked by another model through a many to many relationship. Here's the models themselves class Posts(models.Model): id = models.CharField(max_length

Solution 1:

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))

Solution 2:

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'))

Post a Comment for "Tastypie, Filtering Many To Many Relationships"