我有一个名为Book的模型,它有一个属性when_added,用于存储创建对象实例的时间:
class Book(models.Model):
book_id = models.AutoField(primary_key=True)
title = models.CharField(max_length=30)
# Record the date whenever a new book is added, it will be helpful for showing new arrivals
when_added = models.DateTimeField(auto_now_add=True, blank=True, null= True)
#This helps to print in admin interface
def __str__(self):
return u"%s" % (self.title)
我正在写一个视图,它会返回我在过去两周内添加的书籍列表:
from datetime import date, timedelta
@api_view(['GET'])
def new_arrivals(request, library_id):
"""
List all new arrival books in a specific library
"""
d=date.today()-timedelta(days=14)
print(d)
if request.method == 'GET':
books = Book.objects.filter(which_library=library_id)
books = books.filter(when_added>d)
print(books)
serializer = BookSerializer(books, many=True)
return Response(serializer.data)
我收到一条警告RuntimeWarning: DateTimeField Book.when_added received a naive datetime (2017-11-27 00:00:00) while time zone support is active.
,并且没有任何书籍。
我做错了什么?
答案 0 :(得分:2)
您是否尝试过使用时区感知日期?
from django.utils import timezone
...
# in the new arrivals view
d=timezone.now()-timedelta(days=14)