I just wanted to extract the data of the desired date and time with Django

This is the first post

I wanted to extract the data of the desired date and time

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.

What happened

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.

Time zone setting

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.

in conclusion

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.

References

・ Web Dee Co., Ltd./Service / BLOG / Django How to use field lookup   https://webty.jp/staffblog/production/post-1263/

Recommended Posts

I just wanted to extract the data of the desired date and time with Django
Try to extract the features of the sensor data with CNN
I tried to automatically post to ChatWork at the time of deployment with fabric and ChatWork Api
How to extract features of time series data with PySpark Basics
[Django] I made a field to enter the date with 4 digit numbers
I tried to automatically extract the movements of PES players with software
I tried to extract and illustrate the stage of the story using COTOHA
I wanted to play with the Bezier curve
I tried to open the latest data of the Excel file managed by date in the folder with Python
I tried to get and analyze the statistical data of the new corona with Python: Data of Johns Hopkins University
I failed to install django with pip, so a reminder of the solution
Extract "current date only" and "current date and time" with python datetime.
I tried to extract features with SIFT of OpenCV
Extract the band information of raster data with python
I tried to automate the article update of Livedoor blog with Python and selenium.
I tried to visualize the running data of the racing game (Assetto Corsa) with Plotly
[Challenger Wanted] The fastest Data Loading and Data Augmentation (Kaggle notebook) I can think of
I tried to compare the processing speed with dplyr of R and pandas of Python
It's time to seriously think about the definition and skill set of data scientists
I tried to find the entropy of the image with python
I wanted to solve the Panasonic Programming Contest 2020 with Python
I tried to find the average of the sequence with TensorFlow
I tried to illustrate the time and time in C language
I wanted to worry about execution time and memory usage
I tried to display the time and today's weather w
I can't log in to the admin page with Django3
I want to know the features of Python and pip
I captured the Touhou Project with Deep Learning ... I wanted to.
I sent the data of Raspberry Pi to GCP (free)
I tried to display the point cloud data DB of Shizuoka prefecture with Vue + Leaflet
[Introduction to SIR model] Predict the end time of each country with COVID-19 data fitting ♬
I tried the same data analysis with kaggle notebook (python) and Power BI at the same time ②
How to write offline real time I tried to solve the problem of F02 with Python
I tried to get the number of days of the month holidays (Saturdays, Sundays, and holidays) with python
I tried to analyze the data of the soccer FIFA World Cup Russia tournament with soccer action
I tried the same data analysis with kaggle notebook (python) and Power BI at the same time ①
Return the image data with Flask of Python and draw it to the canvas element of HTML
Give the history command a date and time and collect the history files of all users with a script
I want to record the execution time and keep a log.
[Python] Visualize Arashi's lyrics with WordCloud and try to understand what I wanted to convey to fans in the 20th year of formation.
I tried to describe the traffic in real time with WebSocket
Save the results of crawling with Scrapy to the Google Data Store
I tried to automate the watering of the planter with Raspberry Pi
I want to extract an arbitrary URL from the character string of the html source with python
[Introduction to Python] I compared the naming conventions of C # and Python.
[Introduction to StyleGAN] I played with "The Life of a Man" ♬
I want to output the beginning of the next month with Python
I wanted to challenge the classification of CIFAR-10 using Chainer's trainer
I wanted to solve the ABC164 A ~ D problem with Python
I summarized how to change the boot parameters of GRUB and GRUB2
I tried to expand the size of the logical volume with LVM
To improve the reusability and maintainability of workflows created with Luigi
For the time being, I want to convert files with ffmpeg !!
I want to check the position of my face with OpenCV!
The story of returning to the front line for the first time in 5 years and refactoring Python Django
I tried to improve the efficiency of daily work with Python
I compared while reading the documentation to use Jinja2 with Django
I want to extract the tag information (title and artist) of a music file (flac, wav).
I tried to take the difference of Config before and after work with pyATS / Genie self-made script
I made an npm package to get the ID of the IC card with Raspberry Pi and PaSoRi
Read the data of the NFC reader connected to Raspberry Pi 3 with Python and send it to openFrameworks with OSC