This is the first post
As the title suggests, Django struggled to get data for a specific date and time. I spent a whole day before I could do what I wanted, so I posted it as a memorandum so that I wouldn't forget this hardship, and I hope to reduce the pain when people who see this article do the same thing. ..
-How can I specify month or day when filtering DateTimeField?
It may be a little helpful for those who have troubles such as.
models.py
from django.db import models
class Article(models.Model):
user_id = models.IntegerField()
wirriten_date = models.DateTimeField()
text = models.CharField(max_length=255)
def __str__(self):
return self.text
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('<int:user_id>/<int:date_delta>/', views.index, name=index),
#Here date_delta Specifies how many days ago to get.
]
When I defined models and urls like this, I tried to get all the sentences posted by the user specified by user_id on the date specified by date_delta.
In conclusion, I found that I could send data to the template by writing the view as follows.
views.py
from django.shortcuts import render
from .models import Article
from datetime
def index(request, user_id, date_delta):
date_now = datetime.datetime.now()
wrriten_date = date_now - datetime.timedelta(days=date_delta)
article = Article.objects.filter(user_id=user_id, menu_date__month=menu_date.month, menu_date__day=menu_date.day)
context = {
'article': article,
}
return render(request, 'myapp/index.html', context)
index.html
<p>
{{ article.1.text }}
<!--Caution! article[1]Will result in an error-->
</p>
The biggest problem was how to write the filter method condition of Article.objects. __ month and __ day after menu_date are lookup fields, and you can add conditions to the model variable names.
I learned about lookup fields by looking at the following article. ・ Web Dee Co., Ltd./Service/BLOG/Django How to use field lookup https://webty.jp/staffblog/production/post-1263/
When accessing each data with a template, you can access each data by typing ".data number" as above.
Even if you write views as in the previous section, it will not work well depending on the environment. In that case, changing the time zone setting may work well.
setting.py
TIME_ZONE = 'Asia/Tokyo'
USE_TZ = True
In my case, I set the time zone in the setting as above, and when I set the time zone to Japan, it worked fine.
I hope this article helps someone even a little. Since I am still a beginner in programming and Qiita, there may be many points that I have not reached, but I would like to continue to actively output in the future. If you have any advice such as "This is strange" or "I should do this more!", I would appreciate it if you could comment.
・ Web Dee Co., Ltd./Service / BLOG / Django How to use field lookup https://webty.jp/staffblog/production/post-1263/