Search code examples
pythondjangodatabase

Django: How to get a person whose birthday is today from a database?


Good afternoon, I recently started programming with Django and there was a slight difficulty with displaying the date of birth of a person whose birthday is today from the database, can anyone come across this? model.py

class HapB(models.Model):
    name = models.CharField('Имя', max_length=50)
    last_n = models.CharField('Фамилия', max_length=50)
    Otdel = models.CharField('Отдел', max_length=50)
    date_of_birth = models.DateField('Дата рождения', null=True, blank=True)

    def __str__(self):
        return self.name

Solution

  • I think the best and the simplest approach is this:

    from django.utils import timezone
    
    HapB.objects.filter(date_of_birth__day=timezone.now().date().day, date_of_birth__day=timezone.now().date().month)
    

    Or if your app is not timezone aware:

    from datetime import datetime
    
    HapB.objects.filter(date_of_birth__day=datetime.now().date().day, date_of_birth__month=datetime.now().date().month)