How can i check the model object is 30 days old or not in Django?

536 views Asked by At

Info: I am trying to make monthly billing app. Where a customer can buy a property on a monthly basis payment. i want to change the pending attribute True to False if the customer last payment 30 days old.

It is a schedule based app but i am not using django-crontab or celrey. i can use view funtion for it if user visit the pending_customers page the view can check the all and which customers the last payments date created_at if the created_at datetime is 30 days old. Then the view funtion can change the pending to False.

pending_customers view is working fine but it is changed the pending to False when i visit the page pending_customers. It could not wait for 30 days. if the customer last payment is not 30 days old then how can i hold the view funtion until for 30 days?

models.py

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

    name = models.CharField(max_length=255)
    prop_select = models.ForeignKey(Property, on_delete=models.SET_NULL, null=True)
    created_on = models.DateTimeField(auto_now_add=True)
    pending = models.BooleanField(default=False)

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

    customer = models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL, related_name='payment')
    created_at = models.DateTimeField(auto_now_add=True)
    amount = models.DecimalField(max_digits=17, decimal_places=2, default=0.0)

    def save(self, *args, **kwargs):
        super(Payment, self).save(*args, **kwargs)
        self.customer.pending = True
        self.customer.save()

views.py

def pending_customers(request):

    queryset = Customer.objects.all()

    for i in queryset:
        for d in i.payment.filter(created_at__gte=datetime.now() - timedelta(minutes=30)).order_by('-pk')[:1]:
            d.customer.pending = False
            d.customer.save()

    context = {
        'customers': queryset,
    }
    return render(request, 'customer/pending-customers.html', context)
1

There are 1 answers

7
Tarun Kumar On

I think you're using the wrong condition to mark the pending_customer to False. Right now you're doing the opposite (marking those less than or equal to 30)

From what I gather you want to do created_at__gte=datetime.now() - timedelta(days=30))

That is "get me all the payments that are 30 days or older"