B
B
bituke2021-06-22 10:00:02
Django
bituke, 2021-06-22 10:00:02

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()


How can this be implemented?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Denis Melnikov, 2021-06-22
@bituke

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")

and get it like this
from core.models import Model
Model.get_model()
<QuerySet []>
m1 = Model(title="123")
m1.save()
Model.get_model()
<QuerySet [<Model: 123>]>

ps I do not pretend to be the most correct / best solution, maybe one of the curators will tell you better.

S
Stefan, 2021-06-22
@MEDIOFF

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 question

Ask a Question

731 491 924 answers to any question