python - peewee:如何根据另一个表中跨行的值过滤表中的数据
问题描述
考虑遵循 peewee 支持的 python 代码,如何根据另一个表中跨行的值过滤表中的数据
例如,如果我想在 Note 表中获得一个注释,其中包含所有java
, lambda
,generics
标记customtags
#!/usr/bin/env python3
import peewee
import datetime
db = peewee.SqliteDatabase('test.db')
class Note(peewee.Model):
id = peewee.AutoField()
name = peewee.CharField()
text = peewee.CharField()
created = peewee.DateField(default=datetime.date.today)
class Meta:
database = db
db_table = 'notes'
class CustomTag(peewee.Model):
id = peewee.AutoField()
note = peewee.ForeignKeyField(Note, backref='notes')
tag = peewee.CharField()
class Meta:
database = db
db_table = 'customtags'
indexes = ((("note_id", "tag"), True),)
Note.drop_table()
CustomTag.drop_table()
Note.create_table()
CustomTag.create_table()
note1 = Note.create(name="note1",text='Java 8 lambda with generics')
note1.save()
CustomTag.insert(note=note1, tag='java').on_conflict_ignore(True)
CustomTag.insert(note=note1, tag='lambda').on_conflict_ignore(True)
CustomTag.insert(note=note1, tag='generics').on_conflict_ignore(True)
note2 = Note.create(name="note2",text='Core Java concepts',
created=datetime.date(2018, 10, 20))
note2.save()
CustomTag.insert(note=note2, tag='java').on_conflict_ignore(True)
note3 = Note.create(name="note3",text='Java collection framework',
created=datetime.date(2018, 10, 22))
note3.save()
CustomTag.insert(note=note3, tag='java').on_conflict_ignore(True)
note4 = Note.create(name="note4",text='Java NIO packageJava nio package')
note4.save()
CustomTag.insert(note=note4, tag='java').on_conflict_ignore(True)
notes = Note.select().join(CustomTag, peewee.JOIN.LEFT_OUTER,on=(Note.id == CustomTag.note_id)).order_by(Note.name)
for note in notes:
print('{} with text {} on {}'.format(note.name, note.text, note.created))
我真的不知道如何修改我的代码以获取上面提到的数据,我知道问题出在以下代码中
notes = Note.select().join(CustomTag, peewee.JOIN.LEFT_OUTER,on=(Note.id == CustomTag.note_id)).order_by(Note.name)
解决方案
例如,如果我想在自定义标签中包含所有 java、lambda、泛型标签的 Note 表中获取注释
tags = ['foo', 'bar', 'baz']
query = (Note
.select()
.join(CustomTag)
.where(CustomTag.tag.in_(tags))
.group_by(Note)
.having(fn.COUNT(CustomTag.id) == len(tags)))
推荐阅读
- javascript - 如何在 Express [MEAN] 中发送标头
- django - 模拟 Django 用户的最佳方法是什么?
- c++11 - 将 shared_ptr 作为参数传递给线程函数,会导致错误
- docker - Flask 代码单独运行,但使用 docker 容器化时,页面无法访问
- iphone - 自 IOS 13 更新以来在 Visual Studio Code 中调试 Flutter 不起作用
- java - RestTemplate 获取对象列表 - 为什么使用 ParameterizedTypeReference 而不是对象数组?
- c++ - 如何实例化从使用模板的纯虚拟类继承的对象
- mysql - Connect to local mysql database from django app docker
- java - 如何使单词的最后一个字母变为大写
- rest - Camel Json 验证抛出 NoJsonBodyValidationException