Rectangle 27 0

django Tastypie ManyToMany filter?


class PostCategory(models.Model):
    post = models.ForeignKey(Post, related_name='categories')
    category = models.ForeignKey(Category)


class PostResource(ModelResource):
    user = fields.ToOneField(ProfileResource, 'user', full=True)
    categories = fields.ToManyField(PostCategoryResource, 'categories', full=True)

    class Meta:
        queryset = Post.objects.all()
        resource_name = 'post'
        filtering = {
            # filter by user
            'user': ALL_WITH_RELATIONS,

            #filter by category id
            'categories': ALL_WITH_RELATIONS,
            'category': ALL,
            'id': ['exact'],
        }

Seems like tasty doesn't allow you to filter by virtual field, when the field attribute is represented by lambda.

You can make it work with some modifications:

Note
Rectangle 27 0

django Tastypie ManyToMany filter?


class PostCategory(models.Model):
    post = models.ForeignKey(Post, related_name='categories')
    category = models.ForeignKey(Category)


class PostResource(ModelResource):
    user = fields.ToOneField(ProfileResource, 'user', full=True)
    categories = fields.ToManyField(PostCategoryResource, 'categories', full=True)

    class Meta:
        queryset = Post.objects.all()
        resource_name = 'post'
        filtering = {
            # filter by user
            'user': ALL_WITH_RELATIONS,

            #filter by category id
            'categories': ALL_WITH_RELATIONS,
            'category': ALL,
            'id': ['exact'],
        }

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

Seems like tasty doesn't allow you to filter by virtual field, when the field attribute is represented by lambda.

You can make it work with some modifications:

Note
Rectangle 27 0

django Tastypie ManyToMany filter?


change the resource fields as:

    categories= fields.ManyToManyField(PostResource, attribute=lambda bundle: bundle.obj.categories.all().order_by('name'),
                                       null=True, blank=True, full=True)

also you can use :
lambda bundle: categories.objects.filter(
        categories=bundle.obj, 
        user__id=2
    )
Note