Search code examples
pythondjangoargs

Django entering args for call_command for custom datadump


I am trying to make a custom datadump for Django fixtures so I don't dump everything into one file.

here is my code that throws an error:

extract.py

def create_fixture( filename, *app_name):
    # buffer
    buf = StringIO()
    # unpacks args to list of db tables
    apps = ','.join(map(str, app_name))
    # calls dump data and adds db table to call command
    call_command('dumpdata', apps, indent=2, format='json', stdout=buf)
    # Write to file
    buf.seek(0)
    with open(Path.cwd().joinpath('main', 'fixtures', filename), 'w') as f:
        f.write(buf.read())

class Command(BaseCommand):
    help = 'Dumps database file to fixtures'

    def handle(self, *args, **kwargs):
        #calls function
        create_fixture('country.json','main.Country','main.Cities')
        #prints to console if successful
        self.stdout.write("Dumped Country data!")

If I run python manage.py extract in the console I get the following message:

CommandError: No installed app with label 'main.Country,main.Cities'

But if I write the code like this it works fine but does not use a function:

class Command(BaseCommand):
    help = 'Dumps database file to fixtures'

    def handle(self, *args, **kwargs):
        buf = StringIO()
        call_command('dumpdata', 'main.Country', 'main.Cities',indent=2, format='json', stdout=buf)
        buf.seek(0)
        with open(Path.cwd().joinpath('main', 'fixtures', 'country.json'), 'w') as f:
            f.write(buf.read())
        self.stdout.write("Dumped Country data")

Not sure how to unpack the args correctly and put them into the call_command function


Solution

  • app_name that you are passing in create_fixture is tuple. You dont need to unpack them and convert to string.

    When you do this:

    apps = ','.join(map(str, app_name))
    

    You are actually converting it to list first and then joining all of its elements with ,(comma). Which is giving you just an string 'main.Country,main.Cities'.

    just pass your tuple directly top call_command.

    call_command('dumpdata', *app_name, indent=2, format='json', stdout=buf)