I've written a function to save a QuerySet to a fixture JSON file:
def save_as_fixture(query_set: QuerySet, fixture_name: str, app_label: str='mainapp'):
app_config = apps.get_app_config(app_label)
fixture_dir = os.path.join(app_config.path, "fixtures")
os.makedirs(fixture_dir, exist_ok=True)
fixture_path = os.path.join(fixture_dir, fixture_name)
data = serializers.serialize("json", query_set, indent=2, use_natural_foreign_keys=True, use_natural_primary_keys=True)
with open(fixture_path, 'w') as file:
file.write(data)
But it doesn't save related objects.
I would like it to also save the objects that reference one of the objects of the QuerySet via a ForeignKey
, OneToOneField
, etc. How can I do that?