django-fixture-magic icon indicating copy to clipboard operation
django-fixture-magic copied to clipboard

merge_fixtures should write to stdout

Open florianm opened this issue 5 years ago • 2 comments

Just a consistency issue: dump_objects writes to stdout, while merge_fixtures doesn't.

I want to use the commands from functions, so capturing stdout is easy:

    with open("my_app/fixtures/test_fixture.json", 'w+') as f:
        call_command('dump_object', 'my_app.MyModel *list_of_some_pks, '-k', '-n', stdout=f)
        f.readlines()

Whereas trying to merge fixtures the same way fails (or I fail to capture the output):

with open("my_app/fixtures/test_fixtures_combined.json", 'w+') as f:
        call_command(
            "merge_fixtures",
            "my_app/fixtures/test_fixture_1.json",
            "my_app/fixtures/test_fixture_2.json",
            stdout=f
        )
        f.readlines()

Is this intended behaviour?

florianm avatar Apr 17 '19 01:04 florianm

Update: how to run merge_fixtures from inside a function using Python 3.4+

from contextlib import redirect_stdout

f = io.StringIO()
    with redirect_stdout(f):
        call_command(
            "merge_fixtures",
            "my_app/fixtures/test_fixture_1.json",
            "my_app/fixtures/test_fixture_2.json",
            "my_app/fixtures/test_fixture_3.json",
            "my_app/fixtures/test_fixture_4.json"
        )
        with open("my_app/fixtures/test_fixtures_combined.json", 'w+') as ff:
            ff.write(f.getvalue())

Credit: stackoverflow answer by ForeverWintr

The above workaround does the job for me. Suggestions:

  • add a kwarg output_file (or similar) to specify an output file to write to - if empty, print.
  • instead of printing the output, write to stdout like dump_object does. Unless there's a good reason not to, of course.

Otherwise, thanks for this package, it's perfect solution to quickly carve out some test data from a larger db.

florianm avatar Apr 17 '19 05:04 florianm

This would be a good feature. Both should probably write to stdout and have a --output options.

dopry avatar Nov 17 '22 14:11 dopry