When a QuerySet uses the only function and then uses the print function to print the returned result, an AttributeError is generated
gck123 opened this issue · 1 comments
gck123 commented
Describe the bug
版本:tortoise-orm==0.21.6
这是我的模型定义
class ModelResults(Model):
id = fields.IntField(pk=True)
score = fields.FloatField(default=0, description="评测分数")
total = fields.IntField(description="总用例数")
failed = fields.IntField(description="失败用例数")
passed = fields.IntField(description="通过用例数")
major_type = fields.CharField(max_length=100, null=True, description="大指标")
small_type = fields.CharField(max_length=100, null=True, description="小指标")
ai_model = fields.ForeignKeyField(model_name="models.AIModels", null=True, on_delete=SET_NULL)
task = fields.ForeignKeyField(model_name="models.Tasks", null=True, on_delete=SET_NULL)
class Meta:
table = "tb_model_results"
下面2句是触发问题的代码
res = await ModelResults.filter(ai_model=ai_model).only("score", "major_type").all()
print(res)
当我的模型使用only函数后,如果我在下面对其结果进行打印,会产生AttributeError: 'ModelResults' object has no attribute 'id'
因为Model中的__repr__函数对self.pk进行了判断,最终会走到_get_pk_val函数,由于我使用了only函数所以返回的对象中并没有id这个属性,所以在使用getattr时报了错
以下是出错的地方
def _get_pk_val(self) -> Any:
return getattr(self, self._meta.pk_attr)