M
M
mcrack2021-09-29 17:00:27
Django
mcrack, 2021-09-29 17:00:27

How to put a request in a separate model function in Django?

Hello, for example, there is such a request:
articles = Articles.objects.filter(category=1)....(there are many other conditions here)...order_by('title')

The request is very long and needs to be called in several places, at some point you can forget to take into account something.

Please tell me how to make it so that I can make a request like this:
articles = Articles.published() or Article.objects.published()

Well, I mean, not to write the entire chain of requests, but somehow create a function in the model, how to call it and write a chain in it.

Tried in different ways, but somehow it did not work to make such a function work.

Can anyone give an example of how such a function should look like?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Kuts, 2021-09-29
@mcrack

class Articles(models.Model):
     title = ...
     category = ...
     ...

     @classmethod
     def published(cls):
         return cls.objects \
              .filter(category=1) \
              ....(тут много ещё всяких условий).. \
              .order_by('title')


articles = Articles.published()

But the use of managers for this, as Dmitry noted , is more preferable.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question