Home > Software design >  How to get year from date field(MySQL Database) and display it in a calendar view django?
How to get year from date field(MySQL Database) and display it in a calendar view django?

Time:12-28

I want to get year from date field(MySQL Database) and display it in a calendar view as per the below image:

enter image description here

Given below is my model class:

YEAR_CHOICES = []
for r in range(1980, (datetime.datetime.now().year 1)):
    YEAR_CHOICES.append((r,r))
    
class Persons(models.Model): 
     
    id = models.IntegerField(primary_key=True)
    firstname = models.CharField(max_length=100)
    lastname = models.CharField(max_length=100)
    address = models.CharField(max_length=100)
    dob = models.CharField(max_length=100)
    salary = models.IntegerField
    doj = models.DateField(choices=YEAR_CHOICES, default=datetime.datetime.now().year)
    class Meta:
        db_table = "test"

Instead of only year I am getting data like "Oct. 7, 2021". I want only year neither month or date. And display it in a calender view, like the above image.

Here the year values are retrieved from the mysql database.

Any help will be highly appreciated!
Thank You!!

CodePudding user response:

have you tried:

years={}
persons = Persons.objects.all()
for person in persons:
   years[person.firstname]=person.doj.year

CodePudding user response:

I modified the queryset to get distinct year from datetime coloumn and it works perfectly for me:

def calender(request):
    dateofjoining = Persons.objects.extra(select={"doj": "EXTRACT(YEAR FROM doj)"}).distinct().values_list("doj", flat=True)
    
    person = {
        "Years": dateofjoining
    }
    print(person["Years"][0])
    return render(request, "home.html", person)

But I am unable to display it in a calender view.

  • Related