小编sai*_*ero的帖子

带逻辑运算符的 Tortoise ORM 过滤器

我有两张桌子

class User(models.Model):
    id = fields.BigIntField(pk=True)
    name = CharField(max_length=100)
    tags: fields.ManyToManyRelation["Tag"] = fields.ManyToManyField(
        "models.Tag", related_name="users", through="user_tags"
    )

class Tag(models.Model):
    id = fields.BigIntField(pk=True)
    name = fields.CharField(max_length=100)
    value = fields.CharField(max_length=100)
    users: fields.ManyToManyRelation[User]
Run Code Online (Sandbox Code Playgroud)

我们假设这个虚拟数据

#users
bob = await User.create(name="bob")
alice = await User.create(name="alice")

#tags
foo = await Tag.create(name="t1", value="foo")
bar = await Tag.create(name="t2", value="bar")

#m2m
await bob.tags.add(foo)
await alice.tags.add(foo, bar)
Run Code Online (Sandbox Code Playgroud)

现在我想统计同时拥有标签foo和 的用户baralice在本例中,所以应该是1

下面的查询将为我提供单级过滤,但是如何指定 应该同时user具有foo和?bartags

u = await User.filter(tags__name="t1", tags__value="foo").count()
Run Code Online (Sandbox Code Playgroud)

python orm python-3.x tortoise-orm

3
推荐指数
1
解决办法
6472
查看次数

标签 统计

orm ×1

python ×1

python-3.x ×1

tortoise-orm ×1