I'm new to django so I'm not sure of the proper way to do things (or the convention).
Say I want to make a project which contains my everyday notes.
I'm going to create multiple notes every day (where each note is going to be an instance of a "Note" model).
I want in my project-frontend to have containers, where I start with containers, each of a specific year (say 2020, 2021, ...) and each of these containers contains month containers (Jan, Feb, ...) and each of those contains day containers (1, 2, ..) and each of those contains the notes of this specific day.
Now my question is should, in my backend, make a NoteYear model which has instances of a NoteMonth model which has instances of NoteDay model which has instances of Note model?
I understand that I can filter the objects by the DateTimeField, and put them in different containers in the frontend (Of course I'll have a DateTimeField for each Note instance anyways).
The reason I thought of this is because it should be faster filtering to get to a specific day.
I'd love to hear your opinions!
CodePudding user response:
You may use models as storage objects which means you don't have to define your models based on each and every container.
Accordingly, you may define you models
as follows and use django-template
to iterate and filter by dates into years/months/days.
class Notes(models.Model):
title = models.CharField(max_length=200)
created = models.DateTimeField(default=timezone.now)
updated = models.DateTimeField(default=timezone.now, blank=True)
CodePudding user response:
Models should not be written based on how to present data at the front-end. Models should try to represent and store data in an effective manner.
Here it would be pure fabrication to create models for the year, month and day items. A simple Note
model with a DateTimeField
should suffice, especially if you add a database index to that field such that it can easily filter.
Such model thus looks like:
from django.db import models
class Note(models.Model):
note = models.TextField()
created = models.DateTimeField(auto_now_add=True, db_index=True)
You can then effectively retrieve items for a given year, month, day with:
Note.objects.filter(created__year=2021) # year
Note.objects.filter(created__year=2021, created__month=9) # month
Note.objects.filter(created__year=2021, created__month=9, day=25) # day