Tastypie, filtering many to many relationships

后端 未结 2 563
渐次进展
渐次进展 2021-02-09 15:08

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 =         


        
相关标签:
2条回答
  • 2021-02-09 15:58

    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'))
    
    0 讨论(0)
  • 2021-02-09 16:03

    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))
    0 讨论(0)
提交回复
热议问题