The origin of large-scale and coherent magnetic fields in astrophysical discs is an important and long-standing problem. It is common to appeal to a turbulent dynamo sustained by the magnetorotational instability (MRI) to supply the large-scale field. But research over the last decade, in particular, has demonstrated that various non-ideal magnetohydrodynamic effects can impede or extinguish the MRI, especially in protoplanetary discs. 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 characterize the dynamo and find that it operates 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Ω), and has features in common with other well known 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 magnetic structures dominate. We propose that GI may be key to the dynamo engine not only in young protoplanetary discs but also in some active galactic nuclei and galaxies.