Skip to content

Instantly share code, notes, and snippets.

@fcasco
Created May 25, 2019 22:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fcasco/9d918651e9fac69e9d8a1fbb5b412fec to your computer and use it in GitHub Desktop.
Save fcasco/9d918651e9fac69e9d8a1fbb5b412fec to your computer and use it in GitHub Desktop.
Extra SQL en Django (completo)
from django.db import models
from django.utils improt timezone
class Person(models.Model):
first_name = models.CharField(max_length=42)
last_name = models.CharField(max_length=42)
birth_date = models.DateField()
email = models.EmailField()
@property
def age(self):
now = timezone.now()
years = now.year - self.birth_date.year
if now.month < self.birth_date.month:
age -= 1
elif now.month == self.birth_date.month and now.day < birth_date.day:
age -= 1
return age
@classmethod
def get_values(self):
age_sql = "(EXTRACT(year FROM age(birth_date)) :: int)"
return Person.objects.extra(select={'age': age_sql})\
.values('first_name', 'birth_date', 'age')
@classmethod
def sorted_by_email_provider(self):
email_provider_sql = "(COALESCE(substring(email from '@(.*)$'), ''))"
Person.objects.extra(select={'email_provider': email_provider_sql}).order_by('email_provider')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment