peewee:如何根据另一个表中各行的值来过滤表中的数据

问题描述 投票:2回答:2

考虑以下peewee支持的python代码,如何基于另一个表中各行之间的值来过滤表中的数据

例如如果我想在注释表中获得一个注释,而该表具有java中的所有lambdagenericscustomtags标签,

#!/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)

考虑以下由peewee支持的python代码,如何根据另一个表中各行之间的值来过滤表中的数据,例如如果我想在具有所有java,lambda,...]的注释表中获取一条注释,

例如如果我想在注释表中获得注释,而在customtags中包含所有java,lambda,generics标记
tags = ['foo', 'bar', 'baz'] query = (Note .select() .join(CustomTag) .where(CustomTag.tag.in_(tags)) .group_by(Note) .having(fn.COUNT(CustomTag.id) == len(tags)))

似乎您的插入语句中缺少execute()。应该改成
CustomTag.insert(note=note1, tag='java').on_conflict_ignore(True).execute()
我在此处包含了改进的coleifer答案,结果还包括标签列表...

from peewee import fn filter_tags = ['java', 'lambda', 'generics'] notes = (Note .select(Note, fn.GROUP_CONCAT(CustomTag.tag,',').alias('tags')) .join(CustomTag) .where(CustomTag.tag.in_(filter_tags)) .group_by(Note) .having(fn.COUNT(CustomTag.id) >= len(filter_tags))) for note in notes: print(f'name : {note.name} text: {note.text} tags: {note.tags} created : {note.created}')

python sql peewee
2个回答
1
投票

0
投票
© www.soinside.com 2019 - 2024. All rights reserved.