简体   繁体   中英

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

I have some models defined in Django such as these:

class Post(models.Model):
    text = models.CharField(max_length=50)

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

And I would like to have an external function that, called inside either of these classes, does something related to the class on which it was called.

For example, a ListAll() function that, called inside Post() , lists all Post objects, but called inside Thread , lists all Thread objects.

How would I do this? I've seen replies using __this__ but apparently that references specific class instances, which confuses me a little.

Thank you.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM