Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django values get year from DateTimeField

Tags:

python

django

I have a page where users can search for other users. The search is called with AJAX and the results are returned using JSON with the following code:

return HttpResponse(json.dumps({'users': list(users.values('first_name', 'last_name', 'gender', 'zip_code__city', 'zip_code__state')) }))

I have the users birthday stored in the model with birthday = models.DateTimeField(). I am trying to return just the year of the birthday with the results, but I am having trouble. Returning the whole date would work as well as I can always parse out the year later.

When I try just adding 'birthday' to the arguments in values, I get an error that it is not JSON serializable. I also tried 'birthday__year', but that returned an error that there was no such thing as 'year'.

How do I get the DateTimeField into the list?

like image 592
Hat Avatar asked Feb 12 '14 22:02

Hat


People also ask

How can I get date field in Django?

For DateField : default=date.today - from datetime.date.today() For DateTimeField : default=timezone.now - from django.utils.timezone.now()

What is Klass in Django?

klass may be a Model, Manager, or QuerySet object. All other passed arguments and keyword arguments are used in the get() query. Like with QuerySet.get(), MultipleObjectsReturned is raised if more than one object is found. """

What is timestamped model in Django?

TimeStampedModel - An Abstract Base Class model that provides self-managed created and modified fields.


1 Answers

Build a models.py method to return the year:

models.py

from django.db import models

class MyModel(models.Model):
  birthday = models.DateTimeField()

  def get_year(self):
    return self.birthday.year

Then call this function from your views.py

like image 164
Aaron Lelevier Avatar answered Oct 24 '22 02:10

Aaron Lelevier