django custom commands: how to use reduce repeated code

169 views Asked by At

One of the best features of Django is the MVC way of thinking. I've tried to embrace this as a non-professional programmer. From recommendations on this site, I've been encouraged to start using django custom commands, even for some scripts that will be called daily as a Schedule Windows Task.

I'm finding though, if I have to create a module for every command, it seems to create a lot of duplicate code lines. At least for example the import statements. Is this really the best way to do this? The only solution I can think of is to create a 'generic' custom command module, which takes an argument as the command to run within the generic module.

Am I thinking squarely here? What are the 'best practices' for creating Django Custom Commands?

1

There are 1 answers

0
guyrt On

The best practice is "one task one command." It promotes discoverability when you run manage without commands.

DRYing out your code is absolutely a good idea, but IMHO django commands aren't a major source of code duplication.

Here's a basic command:

from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
<specific imports for my project>

class Command(BaseCommand):
    help = "Produce sample accounts."

    def handle(self, *args, **kwargs):
       # do a thing

That's not that much extra cruft from django itself.

The cleanest way to DRY out your own code is to reuse code in handle() from elsewhere in your application. This ensures that application logic changes are reflected in relevant manage commands, and it often removes long lists of imports because those objects are referenced from core application logic rather than in your manage command.