我有2个类A
和B
:
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
的查询集中?
答案 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):
...