Ryan Saxe
Ryan Saxe

Reputation: 17829

Django unique filtering

Take the following two models:

class Parent(models.Model):
    #...

class Child(models.Model):
    parent = models.ForeignKey(Parent)
    date_made = models.DateField(default=datetime.date.today())
    #... 

goal

Be able to get all Parent instances (no doubles) dependent on a query in the Child instances.

what I have

import datetime
today = datetime.date.today()
a_while_ago = now - datetime.timedelta(days=20)

recent = Child.objects.filter(date_made__gte=a_while_ago)

#I would like, in the most efficient way, to be able to get all the unique
#parents of the children in `recent`. I am completely stumped here...

Upvotes: 0

Views: 1234

Answers (1)

Peter DeGlopper
Peter DeGlopper

Reputation: 37319

One way to do this is to filter directly on the Parent model:

parents = Parent.objects.filter(child__date_made__gte=a_while_ago).distinct()

You can also use a values or values_list query on recent, but that returns parent PKs rather than parent instances:

parent_pks = recent.values_list('parent', flat=True).distinct()

You could then use in_bulk to retrieve the actual instances:

parents = Parent.objects.in_bulk(parent_pks)

I would expect the first to be faster.

Upvotes: 1

Related Questions