模仿Django模型? (简单的实现 - 缺少一些东西)

时间:2011-10-01 17:49:25

标签: python django django-models

我正在尝试模仿django模型:

  

在Django中:

from django.contrib.auth.models import User
if User.objects.get(pk=1) == User.objects.get(username='root')
    print 'True'
else:
    print 'False'
# True is printed
  

我的实施:

 class MyUser:
      def __init__(self, id):
          self.id = id

 class User:
     class objects:
         @staticmethod
         def get(**kwargs):
             return MyUser(1)

if User.objects.get(pk=1) == User.objects.get(username='root')
    print 'True'
else:
    print 'False'
# False is printed

如何纠正我的实施以获得'真实'?

我怎样才能达到同样的效果? 我该怎么做?

2 个答案:

答案 0 :(得分:2)

问题很简单,你没有在你的类上定义__eq__,所以Python不知道如何比较它们。像这样的东西会起作用:

class MyUser(object):
    def __init__(self, id):
        self.id = id

    def __eq__(self, other):
        return self.id == other.id

答案 1 :(得分:0)

这是因为Django的Model实现了__eq__方法:

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

您可以在MyUser课程上实施类似的方法,以达到类似的效果。

另请参阅:the documentation on __eq__