我有以下型号:
class Sample(MAFwBaseModel):
sample_id = AutoField(primary_key=True, help_text='The sample id primary key')
sample_name = TextField(help_text='The sample name')
class Resolution(MAFwBaseModel):
resolution_id = AutoField(primary_key=True, help_text='The resolution id primary key')
resolution_value = FloatField(help_text='The resolution in µm')
class CalibrationMethod(MAFwBaseModel):
method_id = AutoField(primary_key=True, help_text='The primary key for the calculation method')
multiplier = FloatField(default=1., help_text='The multiplication factor of this method')
class Image(MAFwBaseModel):
image_id = AutoField(primary_key=True, help_text='The image id primary key')
sample_id = ForeignKeyField(Sample, on_delete='CASCADE', backref='+')
filename = TextField()
checksum = TextField()
resolution_id = ForeignKeyField(Resolution,on_delete='CASCADE', backref='+')
class ProcessedImage(MAFwBaseModel):
image_id = ForeignKeyField(Image, primary_key=True, backref='+', help_text='The image id, foreign key and primary', on_delete='CASCADE')
value = FloatField(default=0)
有了这个定义,我就可以按照我希望的方式构建数据库。
图像与其他三个表之间的关系非常完美,如下面的 ERD 所示。
现在,我想与 CalibrationMethod 进行交叉联接,为此,我使用以下查询。
cross_join = (ProcessedImage.select(ProcessedImage, CalibrationMethod)
.join(CalibrationMethod, JOIN.CROSS)
.execute()
)
查询本身工作正常,这意味着我得到了我想要的结果,但是当我开始循环行时,我发现了一些奇怪的东西:
for row in cross_join:
# the image_id of ProcessedImage is not what I was expecting:
row.image_id # is the row in Image
row.image_id_id # is the field in ProcessedImage
row.method_id # is the field in CalibrationMethod.
我不明白为什么有时会在属性中添加第二个“_id”。这只是属性的问题,因为数据库中的列都已正确命名。
这让我觉得这不是一个错误,而是一个功能,而且我忽略了一些东西。我缺少什么? 一定有一页文档我跳过了。
我已阅读文档中关于
lazy_load
的页面。如果我指定lazy_load = False,那么row.image_id和row.image_id_id都将是实际的字段值。
此外,如果我保留lazy_load = True并指定object_id_name = 'ref_image_id',则row.image_id将指向图像行,row.ref_image_id将指向字段的值。我宁愿选择相反的情况,即可以更改行的名称而不是字段的名称。
我们遵循 Django 标准,其中:
外键被命名为与您相关的对象的“名词”。最简单的例子是:
sample = ForeignKeyField(Sample, on_delete='CASCADE', backref='+')
然后在您的代码中您可以使用:
image.sample # Resolve the related object.
或者:
image.sample_id # Just the corresponding sample's ID value.