F
F
FFSinit2015-04-17 14:19:43
Django
FFSinit, 2015-04-17 14:19:43

How to update date in django model field when current year changes?

In general, the essence of the problem: there is a model with several fields, on the basis of which the date() model method generates a unique date for each year, writes it to the temp_date field, and next time, instead of generating and writing, it will first check whether the year in temp_date matches today's date. If the year is different, we also generate and write it down, if not, we return the contents of temp_date . It doesn't look very nice, but it suited me until it became necessary to sort the queryset by this date. Because date() is a model method, and temp_date may not contain up-to-date information, using order_by() will not work.
The idea was to rewritetemp_date exclusively by event, namely, the date change to January 1st. This solves all the problems, temp_date contains the actual date and you can use order_by() .
I would not want to write a management command and hang it on cron for this purpose, because we have the application constantly in memory.
How to implement it?
Or maybe there are some alternative solutions to the problem? It just really needs order_by() and not sorted() for sorting.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Filimonov, 2015-04-17
@FFSinit

Updating by cron is a nice solution. You have a date that begs to be in the database and work with the world as a normal field. As I understand it, it is stored for a long time, it is created when the model object is saved, it is updated once a year. There is no need for a method that checks for its relevance, because you do not need this check the vast majority of the time. There should just be a method that fills in the date and does nothing else. Moreover, if after January 1 you will have a peak of visits, you will receive an additional load on the database, plus irrelevant data will remain in it. Binding data update to a query is not good. Much better than crowns, which will make it up-to-date discreetly at 4:03 am on January 1st for everyone at once.
If it was rapidly changing information, then a similar method + cache would be handy.

R
Roman Kitaev, 2015-04-17
@deliro

Use cache instead of temp_date?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question