Created
May 25, 2019 22:16
-
-
Save fcasco/9d918651e9fac69e9d8a1fbb5b412fec to your computer and use it in GitHub Desktop.
Extra SQL en Django (completo)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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