Heisenberg
Heisenberg

Reputation: 495

Where to put custom made functions in Django?

In my models.py I have this class.

import time

class Ticket(models.Model):
    username = models.CharField(max_length=50)
    booking_time = time.time()
    expired = models.BooleanField(default=False)

I want the expired bool to turn to true if 1 hour has been passed since the booking_time but I don't have any idea where should I check for the same thing(I was thinking to make the function in views.py but views are only called when we go to a certain URL, in my case I want to check it every hour).

Upvotes: 0

Views: 299

Answers (2)

Červ Moskomors
Červ Moskomors

Reputation: 71

If you want something like script running in your background in django, you can create for example script.py in your app folder. In that code you can even have

def main()
    while True:
       ....

Then you have to go to wsgi.py (in your project folder) and import your script. So it would be like

import os
import threading

from django.core.wsgi import get_wsgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'weather_raspi.settings')


t = threading.Thread(target=main, args=(args)) #here will you give the function as task and arguments into args
t.start() #this line starts the function
application = get_wsgi_application()

This should work fine for you purposes Hope you'll get it this time

Upvotes: 2

Cyril Jouve
Cyril Jouve

Reputation: 1040

Another solution would be to change you model to use a expiration_time instead of expired boolean, then you can define a function checking the expiration_time vs now()

class Ticket(models.Model):
    ...
    expiration_time = models.DateTimeField()

    def expired(self):
        return self.expiration_time > datetime.now()

or as a query:

expired_tickets = Ticket.objects.filter(expiration_time__gt=Now())

https://docs.djangoproject.com/en/3.1/ref/models/database-functions/#now

Upvotes: 1

Related Questions