writing most common queries as model class method!

38 views
Skip to first unread message

Amir Jamshidi

unread,
Nov 11, 2022, 1:38:44 PM11/11/22
to Django users
Hi, 
I tried to write a classmothods/ instance method in a Model in order to run most common query from the model but got errors like below :

""AttributeError: Manager isn't accessible via ... instances""

example code:

class Profile(model.Model):
    name = model.Charfield(...)
    address = model.Charfield(...)
    ....

    @classmethod
     def count_of_users(cls):
           return cls.objects.all()  #example query

     def all_users(self):
          return self.objects....


My purpose is to have most common and important queries in a method to be called within application. (Its a good way for documenting most common queries as well).What is the best practice for this case?


Chukwudi Onwusa

unread,
Nov 12, 2022, 4:46:20 AM11/12/22
to django...@googlegroups.com
Write that method in your views, and return render(request,'templateName.html', optional) and go to your templates
 and call your desired or important attribute with the instance of the class using Django template tag 
{{class_instanceInMethodInsideView.modelsAtrributeName}} as many attribute as you desire.

Regards....

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/e58df10a-e5c0-40e8-8e0d-5439c04281d8n%40googlegroups.com.

Ryan Nowakowski

unread,
Nov 12, 2022, 9:20:07 AM11/12/22
to django...@googlegroups.com
Hey Amir,

Django best practice is to put all common query methods in the model manager class instead of the model class itself.

- Ryan N

Amir Jamshidi

unread,
Nov 12, 2022, 10:38:48 AM11/12/22
to django...@googlegroups.com

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.


--
___________________________________
Amir JamshidiJam
Computer Engineering at Shiraz University
4|\/|!|2_|_|
Reply all
Reply to author
Forward
0 new messages