Django values get year from DateTimeField
django, python
Solution
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
Problem
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?