Answer the question
In order to leave comments, you need to log in
How to create a function under django model with object filtering?
Let's say there is a portfolio model, I need to create a function, when accessed, all objects with the given filter will be returned, I try to do it like this, but it does not work:
class Portfolio(models.Model):
client = models.ForeignKey(Client, on_delete=models.CASCADE, related_name='portfolio')
name = models.CharField('название', max_length=255)
def get_portfolio(self):
return self.objects.filter(name='123').all()
Answer the question
In order to leave comments, you need to log in
Well, you have the same function for a class object.
Alternatively, make it a class method
class Model(ModelBase):
some = models.CharField(_("Что то "), max_length=250)
@classmethod
def get_model(cls):
return cls.objects.filter(title__icontains="123")
from core.models import Model
Model.get_model()
<QuerySet []>
m1 = Model(title="123")
m1.save()
Model.get_model()
<QuerySet [<Model: 123>]>
Use your manager:
from django.db import models
class PortfolioManager(models.Manager):
def get_portfolio(self):
return self.get_queryset.filter(name='123')
class Portfolio(models.Model):
client = models.ForeignKey(Client, on_delete=models.CASCADE, related_name='portfolio')
name = models.CharField('название', max_length=255)
objects = PortfolioManager()
Portfolio.objects.get_portfolio()
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question