I need all objects, like SomethingModel.objects.all()
for instance.
class SometingModel(model.Model):
def get_all_objects(self):
__[what should i do?]__
return queryset
for example,
queryset = SomethingModel.objects.all()
queryset_by_instance = SomethingModel.objects.get(pk=1).get_all_objects()
queryset == queryset_by_instance <===== True {doesn't matter order}
I need this for data extraction, like
def get_filtered_data(object, object_attribute, min, max):
return object.get_all_objects().filter(object_attribute__lte=max)\
.filter(object_attribute__gte=min)
答案 0 :(得分:11)
您可以使用__class__
获取模型名称,然后获取所有对象。
In [1]: my_instance.__class__
Out[1]: app_name.models.SometingModel # returns the model
In[2]: my_instance.__class__.objects.all()
Out[2]: [..list of objects..] # returns queryset
另一种选择是使用上面@Spectras也提及的_meta.model
。
In[3]: my_instance._meta.model
Out[3]: app_name.models.SometingModel # returns the model
In[4]: my_instance._meta.model.objects.all()
Out[4]: [..list of objects..] # returns queryset
然后在您的模型中,您可以执行以下操作:
class SometingModel(model.Model):
def get_all_objects(self):
queryset = self._meta.model.objects.all()
# can use the below method also
# queryset = self.__class__.objects.all()
return queryset