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
- [Answered ]-How does Django RESTful Framework get user model from token from HTTP header?
- [Answered ]-Django not showing updated data from database
- [Answered ]-How to remove the ?q= from the url in Django
- [Answered ]-Update / Save model date value directly from template?
- [Answered ]-Django makemigrations error when there are 3 custom model in a models.py
Source:stackexchange.com