Python:如何继承和覆盖具有查询集的方法?

时间:2016-10-31 09:27:51

标签: python django inheritance

我有2个类AB

class A(ListView):
        model=Model_name
        def get_queryset(self):
            instance = self.get_user_by_credential(...)
            if instance:
                model_instance = self.model.objects.get(id=instance.id)
                some_objects= self.Model_name.objects.filter(content_id=5, object_id=model_instance.id)
                return some_objects
            return []



class B(A,UserObject):
      model=B_model
      param='foo'
      def get_queryset(self):
            instance = self.get_user_by_credential(...)
            if instance:
                model_instance = self.model.objects.get(id=instance.id, param=param)
                some_objects= Model_name.objects.filter(content_id=5, object_id=model_instance.id)
                return some_objects
            return []

两个类之间的差异仅是param

的查询集中的B

如何覆盖父类A的方法并将参数添加到子类B的查询集中?

1 个答案:

答案 0 :(得分:2)

您可以创建一个get_model_instance方法,然后在A实现中使用它,以便您可以删除B中的实现。

def get_model_instance(self):
    instance = self.get_user_by_credential(...)
    if instance:
         return self.model.objects.get(id=instance.id)
    return None

def get_model_instance(self):
    instance = self.get_user_by_credential(...)
    if instance:
         return self.model.objects.get(id=instance.id, param=param)
    return None

或Daniel Roseman建议

def get_model_instance(self, instance):
     ...