Skip to content

Instantly share code, notes, and snippets.

@dusan87
Created October 9, 2015 16:07
Show Gist options
  • Save dusan87/4306058558723381c6c0 to your computer and use it in GitHub Desktop.
Save dusan87/4306058558723381c6c0 to your computer and use it in GitHub Desktop.
from django.db import models
class Employee(models.Model):
name = models.CharField(max_length=50)
birth_day = models.DateField()
department = models.ForeignKey('Department')
class Department(models.Model):
sector = models.CharField(max_length=255)
# query oldest
oldest = []
for dept in Department.objects.all():
try: # case there is department without employee
employee = dept.employee_set.latest('birth_day')
oldest.append(employee)
except Employee.DoesNotExist:
pass
print oldest
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment