   """
   def list_public_contests(opts \\ []) do
     query =
-      from c in Contest,
-        where: c.timetables_public,
-        join: h in assoc(c, :host),
-        join: cc in assoc(c, :contest_categories),
-        join: p in assoc(cc, :performances),
-        order_by: [
-          {:desc, c.start_date},
-          {:desc, c.end_date},
-          {:desc, c.round},
-          h.name,
-          cc.inserted_at
-        ],
-        preload: [host: {h, [stages: ^stages_query()]}, contest_categories: {cc, :category}]
+      public_contests_query()
+      |> preloaded_with_stages
+      |> order_by([contests: c], desc: c.start_date, desc: c.end_date, desc: c.round)
+      |> order_by([hosts: h, contest_categories: cc], [h.name, cc.inserted_at])
 
     query =
       if opts[:current_only] do

      left_join: u in assoc(h, :users),
      as: :users
  end
end


  # Build a query for fetching public contests.
  defp public_contests_query do
    from c in Contest,
      as: :contests,
      where: c.timetables_public
  end

  # Build a query for fetching stages in display order.
