每次如何为同一数据创建不同的哈希?

时间:2019-06-24 13:13:32

标签: python django django-models hash hash-function

我正在将Account模型对象的哈希添加到Account对象的一列。我正在从某个目标中检索数据并为此创建Account对象。在保存对象之前,我正在计算Account对象的哈希并分配给字段hash_value。然后,我正在检查针对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

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

0 个答案:

没有答案