Search code examples
djangodjango-modelsdjango-rest-frameworkdjango-celery-beat

How to change to BooleanField after True to False every month in Django?


Info: When i create a new customer i want to make pending_customer True which i set with Default value True so it's working fine and after the month the pending_customer make to false automatically.

I also try to make function get_pending_customer who could do it i know this is not the way to what i want to do. It's like a task based funcion which is automatically make pending_customer field True to false after the month. i want to know how can I do this?

Can anyone tell me what is the best way to do this?

models.py

from django.utils.timezone import datetime

class Customer(models.Model):
    """Customer Model"""

    name = models.CharField(max_length=255)
    phone = models.CharField(max_length=11)
    created_on = models.DateTimeField(auto_now_add=True)
    pending_customer = models.BooleanField(default=True)

    """Example""" # I know it's wrong way

    def get_pending_customer(self):
        today = datetime.date.today()
        month = datetime.timedelta(30)
        after_month = today + month
        if after_month:
            panding = self.object
            panding.pending_payment = False
            panding.save()
        return today

Solution

  • I will suggest you use custom-management-commands.

    Write your code in a python file and put it in cron to run every day at a certain time. In the program look for objects older than 30 days and update them for your use case.

    Project structure:

    App_Name/
        __init__.py
        models.py
        management/
            __init__.py
            commands/
                __init__.py
                update_old_data_moreover_30_days.py
        tests.py
        views.py
    

    It's your update_old_data_moreover_30_days.py file:

    from django.core.management.base import BaseCommand, CommandError
        from App_Name.models import Customer 
        from datetime import datetime, timedelta
    
    class Command(BaseCommand):
    
        def handle(self, *args, **options):
            Customer.objects.filter(created_on__lte=datetime.now()-timedelta(days=30)).update(pending_customer=False)
            self.stdout.write('Updated customers older than 30 days')