I would like to use a customer model manager that manipulates a field but does not save to the database. How do I call the model manager function named "with_counts()" in the sample code below.
Is it possible to call it from my view or my templates?
LEVEL = [
('Pro', 'Professional'),
('Int', 'Intermediate'),
('OK', 'Competent')
]
Languages = models.CharField(max_length=25)
Years = models.IntegerField(default=1)
Proficiency = models.CharField(max_length=15, choices=LEVEL, default="Competent")
def __str__(self):
return f'{self.Languages} Level: {self.Proficiency}'
#Do not save to data base.
def with_counts(self):
return self.years * 10;
CodePudding user response:
Just add a @property to your model:
@property
def with_counts(self):
return self.Years * 10;
See https://docs.djangoproject.com/en/4.0/glossary/#term-property and https://docs.python.org/3/library/functions.html#property for further details.
P.S. you should use lower-case model field names.
CodePudding user response:
From the docs:
A custom Manager method can return anything you want. It doesn’t have to return a QuerySet.
So in that can you are right you can just call that as a normal function in your view like this:
views.py:
class your_view(View):
def get(request, *args, **kwargs):
counts = YourModal.objects.with_counts()
# do something with counts
models.py:
class YourModel(models.Model):
objects = models.YourManager()
managers.py:
class YourManager(models.Manager):
def with_counts(self):
return self.years * 10
