Improved speed of query of list of contracts ids of entity.

This adds a new query, but considerably speeds up the total time,
from 10m to <1s. The way Django builds the SQL statement was killing us.