python-3.x 使用Peewe(PostgreSQL)迭代连接查询结果时出错

im9ewurl  于 2022-12-15  发布在  Python
关注(0)|答案(1)|浏览(91)

我无法迭代查询,因为我希望使用Peewee

这些是www.example.com中的相关对象 Models.py

class Conversation(peewee.Model):
    id = peewee.AutoField(unique=True, index=True)
    creation_date = peewee.DateTimeField(default=datetime.now)
    contact_id = ForeignKeyField(Contact, backref='conversation')
    launch_id = ForeignKeyField(Launch, backref='conversation')
    request_data = peewee.TextField(null=True)
    status = peewee.TextField(null=True)
class Contact(peewee.Model):
    id = peewee.AutoField(unique=True, index=True)
    uuid = peewee.CharField(default=shortuuid.uuid, index=True)
    whatsapp_phone = peewee.CharField(index=True, default='')
    status = peewee.CharField(default='init') 
    conversationId = peewee.CharField(null=True)

下面是我尝试迭代的方法:

for conversation in Conversation.select().where(Conversation.launch_id == str(launch_id)):
    print(conversation.contact.id)

这是我得到的错误:

print(conversation.contact.id)
AttributeError: 'Conversation' object has no attribute 'contact'

我尝试改变查询的方式:

query = Conversation.select(Contact).join(Contact).where(Conversation.launch_id == str(launch_id))

但是如果我用同样的方法迭代,我得到了完全相同的错误。

kr98yfug

kr98yfug1#

问题是,由于某种原因,当你已经将外键命名为.contact_id时,你试图访问.contact

class Conversation(peewee.Model):
    id = peewee.AutoField(unique=True, index=True)
    creation_date = peewee.DateTimeField(default=datetime.now)
    # Data will be stored in a column named "contact_id":
    contact = ForeignKeyField(Contact, backref='conversations')
    # Data will be stored in a column named "launch_id":
    launch = ForeignKeyField(Launch, backref='conversations')
    request_data = peewee.TextField(null=True)
    status = peewee.TextField(null=True)

这允许:

query = (Conversation
         .select()
         .where(Conversation.launch == str(launch_id)))
for conversation in query:
    # Access the underlying foreign-key value.
    print(conversation.contact_id)

或者,如果要访问Contact上的其他字段:

query = (Conversation
         .select(Conversation, Contact)
         .join(Contact)
         .where(Conversation.launch == str(launch_id)))
for conversation in query:
    # We now have a "full" Contact instance we can access efficiently:
    print(conversation.contact.id)

请阅读文档:

相关问题