sai*_*ero 3 python orm python-3.x 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和 的用户bar,alice在本例中,所以应该是1。
下面的查询将为我提供单级过滤,但是如何指定 应该同时user具有foo和?bartags
u = await User.filter(tags__name="t1", tags__value="foo").count()
Run Code Online (Sandbox Code Playgroud)
Tortoise-ORM 提供了Q 对象,用于使用|(or) 和&(and) 等逻辑运算符进行复杂查询。
您的查询可以这样进行:
u = await User.filter(Q(tags__name="t1") &
(Q(tags__value="foo") | Q(tags__value="bar"))).count()
Run Code Online (Sandbox Code Playgroud)