首页 > 解决方案 > 每次为相同的数据创建不同的哈希值?

问题描述

我正在将 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

我期望具有相同数据的对象具有相同的哈希值。

标签: pythondjangodjango-modelshashhash-function

解决方案


推荐阅读