【问题标题】:django concatenate filter modeldjango 连接过滤器模型
【发布时间】:2023-03-10 19:27:01
【问题描述】:

为什么这不起作用?我无法将过滤器与另一个变量连接起来?

我觉得自己很笨。

我是 django 的新手,正在尝试使用模型做一些事情。

当我使用时:birthdate__contains='-03-' 工作正常,但使用变量时,url 上什么也没有显示

从 django.shortcuts 导入渲染 从 .models 导入员工 从日期时间导入日期时间

# Create your views here.

def index(request):
    currentMonth = datetime.now().month
    mes_atual = '-'+str(currentMonth)+'-'
    employees = Employee.objects.filter(
                                    birthdate__contains=mes_atual
    )
    context = {
        'employees' : employees
    }
    return render(request, 'index.html', context)

提前致谢

【问题讨论】:

  • 你可以随时使用 print 来调试代码
  • 我在一个单独的文件上使用,谢谢提示

标签: django date model


【解决方案1】:

datetime.now().month 的输出将是 3 而不是 03

要过滤你需要像03这样的日期。

currentMonth = datetime.now()
mes_atual = '-' + str(currentMonth.strftime('%m')) + '-'

请参考this answer 了解详情

您的代码将是:

def index(request):
    #currentMonth = datetime.now().month
    #mes_atual = '-'+str(currentMonth)+'-'
    currentMonth = datetime.now()
    mes_atual = '-' + str(currentMonth.strftime('%m')) + '-'

    employees = Employee.objects.filter(
                                    birthdate__contains=mes_atual
    )
    context = {
        'employees' : employees
    }
    return render(request, 'index.html', context)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-13
    • 2010-10-25
    • 2017-06-22
    • 2013-03-16
    • 2018-03-19
    • 1970-01-01
    相关资源
    最近更新 更多