django - 如果在 only() 方法中未提供字段名,如何防止能够访问 QuerySet 对象的字段?
问题描述
假设我有这个 Django 模型:
class Person(models.Model)
name = models.CharField()
age = models.IntegerField()
然后我在模型上做这个查询:
queryset = Person.objects.filter(name="Joe").only("name") # Notice that I want to only select the name field.
object_list = list(queryset) # Purposefully triggered the database hit by calling list on it.
我如何防止能够做到这一点?:
object_list[0].age # Accessing a field that I did not include in the "only" method triggers an additional hit to the database.
我希望它引发异常或什么都不做,而不是第二次访问数据库。
更新:我已经回答了我自己的问题,但我希望其他人发布他们的答案,看看他们是否有更好的解决方案。
解决方案
覆盖模型的 refresh_from_db 方法并在调用时引发 AttributeError。
class Person(models.Model):
name = models.CharField(max_length=50)
age = models.IntegerField()
def refresh_from_db(self, using=None, fields=None):
"""
This method was overwritten because of the issues addressed in these tickets:
https://code.djangoproject.com/ticket/26481
https://code.djangoproject.com/ticket/22492
https://code.djangoproject.com/ticket/30874
"""
raise AttributeError(
f'Cannot access {self.__class__.__name__}.{fields[0]} because the '
'fieldname was not provided as an argument in the QuerySet.only() '
'method.'
)
推荐阅读
- ruby - ActiveRecord::Base.connection.execute 和纯 sql 返回不同的结果
- python - Pandas - 选择以日期为键的多行和多列
- ssl - OpenShift + Istio 中的 mTLS(客户端证书)
- forms - 如何默认隐藏drupal 8表单元素
- c# - ASP.Net解决方案如何避免生成deps.json文件
- sql - 如何为 liquibase 中的两列设置前置条件?
- c# - 执行另一个实体的插件后如何刷新表单
- bash - 如何使用 bash 将多个短参数连接到单个字符串?
- php - 无法在数据库中创建新条目
- vba - 如何使用类模块修改用户窗体标签的外观?