我有一个模特:
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
在视图中,我想查找在给定日期范围内创建的客户。比方说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()])})
给出:
无法将关键字'date'解析为字段。选择是:地址, 创建,电子邮件,姓名,电话号码,SendEmail,SendSms,姓氏,身份证, 宠物
错误。我也尝试过:
def RecentCustomers(request):
return render_to_response("Customer/AllCustomers.html", {
"customers": Customer.objects.filter(Created >= datetime.date.today() - datetime.timedelta(days=7)})
但是这给了:
语法无效
错误。如何为此过滤日期?
答案 0 :(得分:2)
Customer.objects.filter(Created__gte=datetime.date.today() - datetime.timedelta(days=7))
顺便说一句,最好使用lowercase
名称创建模型字段,模板名称,目录,函数等。
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})
您可能需要查看有关Python中命名约定规则的style guide。