Reputation: 360
Some days ago a guy explained me that on ruby on rails the queries are done on models. Because it gets already saved at your data before be requested on views and the query.
By the way I've learned and had been working until now, I'm setting the query on views.py and passing, through a context variable. So I started to read about Model.Manager and still didn't find a answer to which way is better:
Upvotes: 0
Views: 2152
Reputation: 568
According to the Django idioms want to add some advice that can be useful:
get_by_name_and_domain
method to the user model manager. Also, you can access your model by the model
attribute in the manager.Upvotes: 1
Reputation: 77892
It's a matter of separation of concerns:
Upvotes: 1
Reputation: 11
By default, Django adds a Manager with the name objects to every Django model class. If u have specific business logic, you can make use of managers to override built-in model methods like save() and delete() to add business logic to default database behaviour or you can specifically design some query logic.
file name ---- > models.py
from .managers import ModelNameManager
class ModelName(Base):
title = models.CharField(max_length=255, blank=True, null=True)
headline = models.CharField(max_length=255, blank=True, null=True)
objects = ModelNameManager()
create a file managers.py file in your application file name ---- > managers.py
class ModelNameQuerySet(models.QuerySet):
def by_name(self, id):
return self.filter(id=id)
class ModelNameManager(models.Manager):
def get_queryset(self):
return ModelNameQuerySet(self.model, using=self._db)
def by_name(self, ad):
return self.get_queryset().by_name(id)
in Views.py or any services file file your query will be
import ModelName
obj = ModelName.get_queryset(id)
obj.title
this will return the object based on the query written in managers.
I hope this is helpful.
Upvotes: 1
Reputation: 101
Every model is associated with a Manager (default one is objects
)
>>> from django.contrib.auth.models import User
>>> user = User.objects.all()
>>> type(user)
<class 'django.db.models.query.QuerySet'>
When you need to make any queries to the model you need a manager for this. In the above example user doing a query on objects
manger of User Model.
3-queries made on models.Manager class for each model
- correct interpretation
Upvotes: 1