web2py error: You might need to add explicit type casts

web2py error: You might need to add explicit type casts

我有一个 web2py 应用程序,我必须为其编写一个 SQL 查询。有一个名为homework的table,其中我感兴趣的栏目是receiver。此列包含已收到作业的学生列表。 此专栏由

创建
db.define_table('homework',
Field('title'),
Field('description'),
Field('sender', db.auth_user),
Field('campus_class', db.campus_class),
Field('send_time', type='datetime'),
Field('completion_time_hw', type='integer'),
Field('attached_files', type='list:string'),
Field('created', type='datetime', default=request.now, writable=False, readable=False),
Field('modified', type='datetime', default=request.now, writable=False, readable=False),
Field('send_notification_on', type='datetime',  writable=False, readable=False),
Field('send_status', type='boolean', default=False),
Field('receiver', type='list:reference auth_user'),
)

我需要将这些列表值与另一个名为 student_guardian_relation 的 table 中的列 student 进行比较。

db.define_table('student_guardian_relation',
Field('student',db.auth_user, requires=IS_NULL_OR(IS_IN_DB(db(db.auth_user.user_role == UserRoles.Student),db.auth_user.id,'%(first_name)s %(last_name)s'))),
Field('guardian',db.auth_user, requires=IS_NULL_OR(IS_IN_DB(db(db.auth_user.user_role == UserRoles.Guardian),db.auth_user.id,'%(first_name)s %(last_name)s')))
)

但是当我尝试比较这两个值时,我得到一个错误,内容如下:

< class 'psycopg2.ProgrammingError'> operator does not exist: text = integer LINE 1: ...rdian_relation, homework WHERE (homework.receiver = student_... ^ HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts.

这是我的代码所做的:

print db(db.homework.receiver == db.student_guardian_relation.student).select(db.homework.receiver)

附加信息:

当我写的时候:

print db().select(db.homework.receiver)

我得到了如图所示的接收器列表。 任何帮助将不胜感激。 谢谢!

我终于解决了与int比较行的问题。我用了

db((db.homework.receiver.contains(db.student_guardian_relation.student))

我认为这会比较两个表中的值,而不管类型(至少在我的情况下它是这样做的)并且您可以通过在这个表上构建来进一步扩展您的查询。

请注意,db.homework.receiver 是一个 list:reference 类型字段,因此它存储记录 ID 列表,而不是单个 ID。因此,您必须使用 .contains 运算符而不是 == 来检查特定 ID 是否包含在列表中。

在内部,list:reference 字段存储为带有“|”的文本字段分隔 ID 的字符(例如,“|1|5|12|32|”)。 web2py DAL 自动处理这种格式和 Python 列表之间的转换。无论如何,这就是您使用 == 运算符触发有关类型不匹配的错误的原因(即,您的查询正在将字符串与整数进行比较)。

有关详细信息,请查看相关 documentation