Refactor query to support filter by related models