Tastypie,过滤多对多的关系

Sha*_*ane 6 python django tastypie

我有两个模型通过多对多关系由另一个模型链接.

这是模型本身

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')
Run Code Online (Sandbox Code Playgroud)

和tastypie资源

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'
Run Code Online (Sandbox Code Playgroud)

在posttags表上有一个删除标志,当PostTags中的删除标志为0时,是否只能返回链接结果?

我在tastypie中尝试了这个过滤器属性,但它似乎只关心链接表中的标志(即标签或帖子)而不是实际的表进行链接.

小智 8

您可以使用显示表名和字段名的lambda bundle属性过滤字段.

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