Django Model实例可哈希吗? [英] Are Django Model instances Hashable?

查看:71
本文介绍了Django Model实例可哈希吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Django模型实例可哈希吗?例如,我可以将Django Model实例用作字典键,还是创建一组唯一的模型?

Are Django Model instances Hashable? For example, can I use a Django Model instance as a dictionary key, or create a Set of unique models?

如果它们是可哈希的,是什么导致两个Django Model实例被认为是一样的吗?它会天真地实现Hashable,以便仅在内存中它们是相同的Python对象时才认为它们是相同的,还是以某种方式使用Model实例的值?

If they are Hashable, what causes two Django Model instances to be considered the same? Does it implement Hashable naively such that it only consider them to be the same if they are the same Python object in memory, or does it use the value of the Model instance in some way?

推荐答案

模型实例是可哈希的。如果它们是相同类型的模型并且具有相同的主键,则认为它们是相同的。您可以在定义的> django.db.models.base :

Model instances are Hashable. They are considered to be the same if they are Models of the same type and have the same primary key. You can see this defined in django.db.models.base:

class Model(object):

    ...

    def __hash__(self):
        return hash(self._get_pk_val())

    ...

    def __eq__(self, other):
        return isinstance(other, self.__class__) and \
               self._get_pk_val() == other._get_pk_val()

这篇关于Django Model实例可哈希吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆