这个问题已经在这里有了答案: > Getting upcoming birthdays using ‘date of birth’ DateField 3个
我正在尝试获取未来15天内生日的人的名单.我有这个模型:
class Cliente(models.Model):
nombre = models.CharField(max_length=100)
fecha_nacimiento = models.DateField(default=datetime.date.today,blank=True,null=True)
telefono_numero = models.CharField(max_length=10, null=True)
direccion = models.CharField(max_length=100, null=True)
otro_contacto = models.CharField(max_length=150, null=True)
def __unicode__(self):
return u'%s' % self.nombre
我的字段“ fecha_nacimiento”(出生日期)是一个models.DateField.当我可以使用以下方法获得生日在当月的人时:
mes = date.today().month
cumplen_mes = Cliente.objects.filter(fecha_nacimiento__month=mes)
并且我有一个查询集,指定在哪个月份与谁生日,但是我只想查看接下来15天内的生日.我尝试使用过滤器,但不知道如何连接过滤器,即:
我可以做到Cliente.objects.filter(fecha_nacimiento__day = a_day)
我读到有关GTE&但不能与此过滤器结合使用fecha_nacimiento字段.
解决方法:
通常,您可以通过向过滤器传递多个关键字参数来应用多个过滤器,
Cliente.objects.filter(field1='foo', field2='bar')
或通过链接过滤器调用:
Cliente.objects.filter(field1='foo').filter(field2='bar')
对于您的特定问题,您可以计算15天后的日期.
如果该日期是当前月份,则查询是直接进行的(请注意,它仅适用于Django 1.9)
today = date.today()
fifteen_days = today + timedelta(days=15)
Cliente.objects.filter(
fecha_nacimiento__month=today.month,
fecha_nacimiento__day__gte=today.day, # we don't want birthdays that have already happened this month
fecha_nacimiento__day__lte=fifteen_days.day,
)
如果那个日期是下个月,那就更难了.您要么想要本月的日期,要么想要15天内的下个月的日期.在Django中,您可以使用Q()对象进行OR查询.
Cliente.objects.filter(
Q(fecha_nacimiento__month=today.month, fecha_nacimiento__day__gte=fifteen_days.day) |
Q(fecha_nacimiento__month=fifteendays.month, fecha_nacimiento__day__lte=fifteen_days.day)
)
放在一起,您将:
today = date.today()
fifteen_days = today + timedelta(days=15)
queryset = Cliente.objects.all()
if today.month == fifteen_days.month:
queryset = queryset.filter(
fecha_nacimiento__month=today.month,
fecha_nacimiento__day__gte=fifteen_days.day,
fecha_nacimiento__day__lte=fifteen_days.day,
)
else:
queryset = queryset.filter(
Q(fecha_nacimiento__month=today.month, fecha_nacimiento__day__gte=fifteen_days.day) |
Q(fecha_nacimiento__month=fifteendays.month, fecha_nacimiento__day__lte=fifteen_days.day)
)
上面的查询未经测试,因此可能存在语法错误,或者可能不是很正确,但是我认为这种方法会行得通.
标签:python,django
来源: https://codeday.me/bug/20191027/1946048.html