pietà pietà - 1 month ago 6
Python Question

Python: How to inherit and override a method having a queryset?

I have 2classes

A
and
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 []


the difference between the 2 classes is only the
param
in the queryset of
B


How can I override the method of the parent class
A
and add a parameter to the queryset of the child class
B
?

Answer

You could just make a get_model_instance method and then use that inside the A implementation so that you can remove the implementation in 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

or as suggested by Daniel Roseman

def get_model_instance(self, instance):
     ...