Monu Yadav
Monu Yadav

Reputation: 570

Filter Django models based on date comparision

I have a Subscription models that has an end_date attribute.

class Subscription(models.Model):
    client = models.OneToOneField(ClientProfile, on_delete=models.CASCADE)
    trainer = models.ForeignKey(TrainerProfile, null=True, blank=True,
        on_delete=models.SET_NULL, limit_choices_to={'is_staff': True})
    plan = models.ForeignKey(Plan, on_delete=models.CASCADE)
    transaction = models.OneToOneField(PaymentHistory, on_delete=models.CASCADE)
    start_date = models.DateTimeField()
    end_date = models.DateTimeField()

I want to send an email to the user having subscription to notify once:

(subscription.end_date - timezone.now()).days < 3

How would I filter data from django based on these type of comparision in filter() rather than reading all the Subscription objects in the memory.

Upvotes: 0

Views: 47

Answers (1)

kamilyrb
kamilyrb

Reputation: 2627

Firstly, you can find 3 days from now. After you can use end_date__lte param. Like that:

comparing_date =  datetime.datetime.today() + datetime.timedelta(days=3)
subscriptions =  Subscription.objects.filter(end_date__lte=comparing_date)

Upvotes: 2

Related Questions