Wednesday, February 10, 2010

Filtering list in Django

Right so .filter is the way to get data from a query set. How do you go about filtering a set based on on a different set?

For SQL heads this is usually done by WHERE ID IN () or WHERE ID CONTAINS()

What you need to do in Django is convert the () part into a list and filter as normal

random_questions = All_Questions.objects.filter(pk__in=list(ordered_questions.values_list('id', flat=True))).order_by('?')

Flat = true implies the results are returned efficiently [1,2,3] as opposed to [(1,),(2,),(3,)]

No comments:

Post a Comment