Tastypie, filtering out many, many relationships

I have two models that are connected by another model through the attitude of many to many.

Here the models themselves

class Posts(models.Model): id = models.CharField(max_length=108, primary_key=True) tags = models.ManyToManyField('Tags', through='PostTags') class Tags(models.Model): id = models.CharField(max_length=108, primary_key=True) posts = models.ManyToManyField('Posts', through='PostTags') class PostTags(models.Model): id = models.CharField(max_length=108, primary_key=True) deleted = models.IntegerField() post_id = models.ForeignKey('Posts', db_column='post_field') tag_id = models.ForeignKey('Tags', db_column='tag_field') 

And tastypie resources

 class PostsResource(ModelResource): tags = fields.ToManyField('django_app.api.TagsResource', 'tags', null=True) class Meta: queryset = Posts.objects.filter(deleted=0) resource_name = 'posts' class TagsResource(ModelResource): posts = fields.ToManyField('django_app.api.PostsResource', 'posts', null=True) class Meta: queryset = Tags.objects.filter(deleted=0) resource_name = 'tags' 

There is a remote flag in the posttags table, is it possible to return only related results when the remote flag in PostTags is 0?

I tried this filter attribute in tastypie, but it seems that it only cares about the flag in the related table (i.e. tags or messages), and not the actual table makes the link.

+6
source share
2 answers

You can filter the fields using the lambda bundle attribute, which displays the table name and field name.

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

Wow ... I watched all day! "attribute" is exactly what I was looking for. I almost started to crack my models to filter them out of despair.

From the resource field documentation for ToManyField:

Provides access to related data through a connection table.

This subclass requires the Djangos ORM layer to work correctly.

This field also has special behavior when working with an attribute in which it can accept a call. For example, if you need to filter the inverse relation, you can do something like:

 subjects = fields.ToManyField(SubjectResource, attribute=lambda bundle: Subject.objects.filter(notes=bundle.obj, name__startswith='Personal')) 
+1
source

Source: https://habr.com/ru/post/920870/


All Articles