我在访问代码中的交叉引用(through)模型时遇到问题。你知道吗
从下面的代码可以看出,我的交叉引用模型中有一个字段,我想通过声音文件模型来选择它,但我似乎不知道如何选择。你知道吗
我对python和peewee还不熟悉,所以请容忍我。我有编程经验,但不是python。如果你能提供任何帮助,我将不胜感激。你知道吗
一小块土地: 我有一个存储库,在内存中保存一个声音文件记录列表。我正在遍历这些记录,并尝试访问交叉引用模型(该模型中的字段)。每个模型扩展的BaseModel只是建立了Meta类。你知道吗
声音文件模型
from peewee import *
from OgmaChatBot.entities.BaseModel import BaseModel
class SoundFile(BaseModel):
file_name = TextField()
short_name = TextField()
command_available = IntegerField(constraints=[SQL("DEFAULT 0")])
@staticmethod
def get_all():
return SoundFile.select()
@staticmethod
def get_one(key):
return SoundFile.get(SoundFile.id == key)
事件模型
from peewee import *
from OgmaChatBot.entities.BaseModel import BaseModel
class Event(BaseModel):
event = TextField()
@staticmethod
def get_all():
return Event.select()
@staticmethod
def get_one(key):
return Event.get(Event.id == key)
SoundEvent模型(交叉引用模型)
from peewee import *
from OgmaChatBot.entities.BaseModel import BaseModel
from OgmaChatBot.entities.Event import Event
from OgmaChatBot.entities.SoundFile import SoundFile
class SoundEvent(BaseModel):
sound_file = ForeignKeyField(
column_name='sound_file_id',
field='id',
model=SoundFile,
backref='sound_event'
)
event = ForeignKeyField(
column_name='event_id',
field='id',
model=Event,
backref='sound_event'
)
username = TextField(null=True)
@staticmethod
def get_all():
query = (SoundEvent
.select(SoundEvent, SoundFile, Event)
.join(SoundFile)
.switch(SoundEvent)
.join(Event))
return query
@staticmethod
def get_one(key):
query = (SoundEvent
.select()
.join(SoundFile)
.switch(SoundEvent)
.join(Event)
.where(SoundEvent.id == key))
return query
根据OP的评论:
有两种方法。由于每个声音文件可能有0..n个SoundEvent对象,因此我们将执行以下操作:
既然你已经宣布SoundEvent.sound\u文件使用
backref="sound_event"
外键,您也可以这样做,这是等效的(尽管考虑将backref sound\u事件设为复数):最后一个选择是尝试使用
prefetch()
更有效地执行此操作,这在其实现中有点复杂,并且只能在分析之后使用:你的问题不清楚你想做什么…但这里有一些基于你共享的staticmethod的例子:
然后可以打印所有文件名:
或打印所有事件:
或者,也可以从
SoundFile
开始列出所有事件:等效于两个连接:
我希望这能澄清问题。你知道吗
相关问题 更多 >
编程相关推荐