Páginas

sexta-feira, agosto 29, 2014

Grouping Django querysets

This is a simple tip for group or "sum" or "make a union" of Django query sets.

This is the case:

class SomeModel(models.Model):
    name = models.CharField(max_length=100)
    short= models.CharField(max_length=10)

fst_exemple = SomeModel.objects.create(
    name="Luiz Guilherme", short="LG")
scd_exemple = SomeModel.objects.create(
    name="Guilherme Silva", short="Silva")

lg_cases = SomeModel.objects.filter(short="LG")
silva_cases = SomeModel.objects.filter(short="Silva")

# getting the two cases
lg_or_silva = lg_cases | silva_cases

# starting from empty
starting_from_none = SomeModel.objects.none()

# adding cases on empty:
# Usefull for loops (this is my reason for write this)
starting_from_none |= lg_or_silva

I hope to save somebody with this.

Nenhum comentário: