gpt4 book ai didi

python - 如何查找给定日期范围内创建的对象?

转载 作者:行者123 更新时间:2023-12-01 04:50:28 24 4
gpt4 key购买 nike

我有一个模型:

class Customer(models.Model):
Name = models.TextField(blank=False)
Surname = models.TextField(blank=False)
PhoneNumber = models.TextField()
Address = models.TextField()
SendSms = models.BooleanField(default=True)
SendEmail = models.BooleanField(default=True)
Email = models.TextField()
Created = models.DateField(auto_now_add=True)

@classmethod
def create(cls, name, surname, phoneNumber, address , sendSms, sendEmail, email):
customer = cls(Name=name, Surname=surname, PhoneNumber=phoneNumber
, Address=address, SendSms=sendSms, SendEmail=sendEmail
, Email=email)
customer.save()
return customer

在 View 中,我想查找在给定日期范围内创建的客户。就说7天吧。

下面的代码:

def RecentCustomers(request):
return render_to_response("Customer/AllCustomers.html", {
"customers": Customer.objects.filter(
date__range=[datetime.date.today() - datetime.timedelta(days=7), datetime.date.today()])})

给予:

Cannot resolve keyword 'date' into field. Choices are: Address, Created, Email, Name, PhoneNumber, SendEmail, SendSms, Surname, id, pet

错误。我也尝试过:

def RecentCustomers(request):
return render_to_response("Customer/AllCustomers.html", {
"customers": Customer.objects.filter(Created >= datetime.date.today() - datetime.timedelta(days=7)})

但是这给出了:

invalid syntax

错误。我如何过滤日期?

最佳答案

Customer.objects.filter(Created__gte=datetime.date.today() - datetime.timedelta(days=7))

顺便说一下,创建模型字段、模板名称、目录、函数等时最好始终使用小写名称。

<小时/>
from django.shortcuts import render

def recent_customers(request):
customers = Customer.objects.filter(created__gte=datetime.date.today() - datetime.timedelta(days=7))
return render(request, "customer/all_customers.html", {"customers": customers})

您可能想看看 style guide关于Python中的命名约定规则。

关于python - 如何查找给定日期范围内创建的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28600958/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com