Reputation: 17
This is a digital library system. When borrow end_date has expired, borrow status will be updated automatically to 1 (End), table book column stock will be updated adding one stock, and automatically inserting new content value in table notification.
class Borrow(models.Model):
status = models.CharField(max_length=1, choices=[('0', 'Process'),('1', 'End')], default=0)
book = models.ForeignKey('models.Book', on_delete=models.CASCADE, related_name='borrow_book')
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
end_date = models.DateTimeField()
class Book(models.Model):
stock = models.IntegerField(blank=True, null=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Notification(models.Model):
content = models.CharField(max_length=255, blank=True, null=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
How to make an automatic update query in table borrow column status, table book column stock, and insert in table notification when end_date > DateTime.now() ?
Upvotes: 0
Views: 176
Reputation: 2268
I would make a management command and then create a Cron / Scheduled Task to run it Hourly.
There are packages like django-crontab
and django-cron
that could also do this (I assume?), but I've never used either and have stuck with the ol' Default Linux Crontab
Note: I left out creating Notification
from django.core.management.base import BaseCommand
from django.core.management import call_command
class Command(BaseCommand):
help = 'Ran Hourly With a Cron'
def handle(self, *args, **kwargs):
from app.models import Barrow
from datetime import datetime
# Fetch List
l = Borrow.objects.filter(status='0', end_date__lte=datetime.now())
# Update stock
# F() means you don't need to fetch the value to update it!
from django.db.models import F
for i in l:
b = i.book
b.stock += F('stock') + 1
b.save()
# update List
l.update(status='1')
This would probably be a better way to update the count, especially if there's multiple barrows for a single book.
from django.db.models import Count
for i in l.values('book').annotate(count=Count('pk')):
# i = { 'book': {book__pk}, 'count': total_int }
b = Book.objects.get(pk=i['book'])
b.stock += F('stock') + i['count']
b.save()
But this might not be the best idea because a book could be late to be returned and then your count is off.
Upvotes: 0