Tech
Tech

Reputation: 945

How to compare dates with django

I have a Post model which has vip membership end time. I want to count active memberships.

My model:

class Post(models.Model):
    title = models.CharField(max_length=250,verbose_name ='Başlık')
    image =  models.ImageField(upload_to=upload_location, null=True, blank=True,verbose_name ='Vitrin Fotoğrafı')
    vip = models.BooleanField(default=False,verbose_name ='Vip')
    phone = models.CharField(max_length=11,verbose_name ='Telefon')
    vipend = models.DateTimeField(auto_now=False,auto_now_add=False,null=True,blank=True,verbose_name ='Vip Bitiş')

My view:

def yonetim(request):

endvipcount = Post.objects.fiter(vip=True,vipend<datetime.now()).count() # This part is obviously wrong # 

context = {
    "endvipcount": endvipcount ,

    }
 return render(request, "yonetici.html", context)

Error:

endvipcount = Post.objects.fiter(vip=True, vipend < datetime.now()).count()
                                                       ^
SyntaxError: invalid syntax

I want active and passive vip member counts. What is the ideal way of doing it?

Upvotes: 2

Views: 105

Answers (1)

Navid Zarepak
Navid Zarepak

Reputation: 4208

For SQL queries which use the WHERE clause you should use Django field look ups (see doc links)

You can use __lt:

Post.objects.fiter(vip=True, vipend__lt=datetime.now()).count()

Which means any Post objects where the vip field is true and the vipend field is less than now().

You can also use __date__lt if you want to ignore the time component of the field.

Django doc: lt
Django doc: date

Upvotes: 8

Related Questions