python - 每次为相同的数据创建不同的哈希值?
问题描述
我正在将 Account 模型对象的哈希添加到 Account 对象的一列中。我正在从某个目标检索数据并为此创建 Account 对象。在保存对象之前,我正在计算 Account 对象的哈希值并分配给字段 hash_value。然后我正在检查帐户中是否存在哈希值字段。避免不必要的更新。但是每次插入之前生成的哈希值都是不同的。为什么?
我尝试比较来自目标和当前帐户的 obj 中的每个字段..这些是相同的。
# Account model
class Account(models.Model):
uuid = models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True)
application_id = models.ForeignKey(Applications, related_name="account_application_id", on_delete=models.CASCADE)
employee_id = models.TextField(null=True)
username = models.TextField(null=True)
display_name = models.TextField(null=True)
mail = models.TextField(null=True)
department = models.TextField(null=True)
company = models.TextField(null=True)
description = models.TextField(null=True)
entitlements = models.TextField(null=True)
hash_value = models.BigIntegerField(null=True)
def __hash__(self):
hash_sum_value = hash(
(
# self.uuid, no two uuid can be same
str(self.application_id.uuid), # include only uuid of application in hash
str(self.employee_id),
str(self.username),
str(self.display_name),
str(self.mail),
str(self.department),
str(self.company),
str(self.description),
str(self.entitlements)
)
)
return hash_sum_value
# checking hash present to avoid unnecessary updation.
obj = Account()
# some code to add values in obj
if entity_type == 'account':
try:
obj.hash_value = hash(obj)
except TypeError:
logging.info("Account info " + str(obj))
logging.error("Unable to hash object: " + str(obj.username))
if Account.objects.filter(hash_value=obj.hash_value).exists():
# never comes here
logging.info("Hash matched for acc " + obj.username)
continue
我期望具有相同数据的对象具有相同的哈希值。
解决方案
推荐阅读
- c# - 有什么方法可以设置 ResourceDictionary 键以匹配类名?
- ajax - Chrome 扩展程序卸载上的 Ajax
- python - 如何管理 Pandas 中的子图?
- c# - c# 可以保存一个List
在另一个应用程序中反序列化? - .net-core - 在法语 Windows 上强制使用英语的 dotnet CLI
- angular - 在 Ionic 3 应用程序中免费显示来自 admob 的横幅
- c# - 授权处理程序
- apache-spark - 如何使用 pyspark 写入 Kafka?
- javascript - 使用 Google Charts API 隐藏图表
- python-3.x - Mac 和 Ubuntu 中 icu 的导入错误,尽管 pyicu 安装正确