The origin of large-scale and coherent magnetic fields in astrophysical discs is an important and long standing problem. Researchers commonly appeal to a turbulent dynamo, sustained by the magneto-rotational instability (MRI), to supply the large-scale field. But research over the last decade in particular has demonstrated that various non-ideal MHD effects can impede or extinguish the MRI, especially in protoplanetary disks. In this paper we propose a new scenario, by which the magnetic field is generated and sustained via the gravitational instability (GI). We use 3D stratified shearing box simulations to characterise the dynamo and find that it works at low magnetic Reynolds number (from unity to ~100) for a wide range of cooling times and boundary conditions. The process is kinematic, with a relatively fast growth rate ($< 0.1 Omega$), and it shares some properties of mean field dynamos. The magnetic field is generated via the combination of differential rotation and spiral density waves, the latter providing compressible horizontal motions and large-scale vertical rolls. At greater magnetic Reynolds numbers the build up of large-scale field is diminished and instead small-scale structures emerge from the breakdown of twisted flux ropes. We propose that GI may be key to the dynamo engine not only in young protoplanetary discs but also in some AGN and galaxies.