[Answered ]-Is it possible for a function to reference the class on which it's called?

1👍

This is a job for a mixin, which can be added to any class.

class ListAll:
    def list_all(self):
        return self.__class__.objects.all()

Add it to the class:

class Post(ListAll, models.Model):
     ...

And use it:

my_post_obj.list_all()

I hope this is an example though, as it would be far better to just pass the model class itself into wherever you want to list the objects.

1👍

You can use functions inside the model and those can be called with class objects

class Thread(models.Model):
    title = models.CharField(max_length=50)

    def listAll(self):
        return self.objects.all() # a function that would return all objects

As per comments If you have requirements of using a single function for many models then you can load a model dynamically by its name. I won’t say that its recommended or anything but it works perfectly.

import importlib
model_module = importlib.import_module('app_name.models.models') 
# remember this example refers to loading a module not its class so if you 
# have a file models.py containing all the models then this should be perfect
model_object = model_module.model_name # now you have loaded the model
data = model_object.objects.all() # apply whatever you want now

Leave a comment