当我使用Peewee连接两个表并从两个表中选择具有相同名称的属性时,最后一个表将覆盖其他表。例如,使用以下表格:
from peewee import *
db = SqliteDatabase(":memory:")
class BaseModel(Model):
class Meta:
database = db
class Module(BaseModel):
name = CharField()
class Student(BaseModel):
name = CharField()
member = ForeignKeyField(Module, related_name="members", null=True)
db.create_tables([Module, Student], safe=True)
这样的数据:
history_id = Module.create(name="History")
science_id = Module.create(name="Science")
Student.create(name="Tim", member=history_id)
Student.create(name="Mike", member=science_id)
选择这样:
modules = Module.select(
Student.name,
Module.name
).join(
Student,
on=(Module.id == Student.member)
).group_by(Module).dicts()
我明白了:
{'name': 'History'}
{'name': 'Science'}
或者,如果我在Select:
中反转顺序 {'name': 'Tim'}
{'name': 'Mike'}
Peewee是否提供了解决此问题的方法?
答案 0 :(得分:0)
刚才意识到Peewee的alias()
可以是used on columns以及表格:
modules = Module.select(
Module.name.alias("module_name"),
Student.name.alias("student_name")
).join(
Student,
on=(Module.id == Student.member)
).group_by(Module).dicts()
给出:
SELECT "t1"."name" AS module_name, "t2"."name" AS student_name FROM "module" AS t1 INNER JOIN "student" AS t2 ON ("t1"."id" = "t2"."member_id") GROUP BY "t1"."id", "t1"."name"
和
{'module_name': 'History', 'student_name': 'Tim'}
{'module_name': 'Science', 'student_name': 'Mike'}