title: Automatically set a virtual field in an Ecto.Schema on an Ecto.Query
body: <p>In <a href="https://youtu.be/YQxopjai0CU?t=1616" rel="nofollow noreferrer">this talk</a> at the linked time the speaker describes how to automatically set a field in an Ecto.Schema based on a virtual field by piping the changeset through a conversion function like this:</p>
  
  <pre><code>defmodule MusicDb.Track do
    use Ecto.Schema
  
    schema "tracks" do
      field :title, :string
      field :duration, :integer
      field :duration_string, :string, virtual: true
  
      timestamps()
    end
  
    def changeset(track, attrs) do
      track
      |&gt; validate...
      |&gt; convert_duration_string
    end
  end
  </code></pre>
  
  <p>This is used to convert a user input of 3:25 to 205 for example.</p>
  
  <p>How do I do the other direction? When I query a <code>Track</code> from the <code>Repo</code> the virtual field <code>duration_string</code> is <code>nil</code>. How do I install a function to automatically calculate and set the virtual field when a schema of a certain struct is queried?</p>