Skip to content

Instantly share code, notes, and snippets.

@maxwellcc
Created February 16, 2021 16:24
Show Gist options
  • Save maxwellcc/b1e247fb006619a8a2a1b81303eb4f90 to your computer and use it in GitHub Desktop.
Save maxwellcc/b1e247fb006619a8a2a1b81303eb4f90 to your computer and use it in GitHub Desktop.
Como criar um modelo Django que herde de classe pai como proxy, com restrições na consulta
class Person(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
age = models.PositiveIntegerField()
def __str__(self):
return self.first_name
class Majority(models.Manager):
def get_queryset(self):
return super(Majority, self).get_queryset().filter(age__gte=18)
class MajorityPerson(Person):
class Meta:
proxy = True
objects = Majority()
def __str__(self):
return f'{self.first_name} {self.last_name}'
def clean(self):
if self.age < 18:
raise ValidationError('It cannot be under 18 years.')
@maxwellcc
Copy link
Author

Aqui a classe MajorityPerson herda os campos de Person, porém, só exibe e salva pessoas maiores de 18 anos.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment