我有两张桌子
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)