pythondjangodjango-managersdjango-manage.pydjango-management-command

Command object has no attribute meta, Django management commands


I am trying to run a one time management command to pre-populate a db.

Here is the model:

class ZipCode(models.Model):
    zip_code = models.CharField(max_length=7)
    latitude = models.DecimalField(decimal_places=6, max_digits =12)
    longitude = models.DecimalField(decimal_places=6, max_digits =12)

and here is the management command:

  from django.core.management.base import BaseCommand
    from core.models import ZipCode

    class Command(BaseCommand):
        def populate_db(self):
            zip_code_object = ZipCode(zip_code='10566', latitude = 10.2, longitude= 43.4) #test data to see if I could get it working
            ZipCode.save(self)

        def handle(self, *args, **options):
            self.populate_db()

But when I run python3.6 manage.py populate_zip_code_db it returns

 File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/models/base.py", line 741, in save
    for field in self._meta.concrete_fields:
AttributeError: 'Command' object has no attribute '_meta'

Does anyone know how to get this working? I just discovered management commands so I am clueless.


Solution

  • Instead of ZipCode.save(self) it should be zip_code_object.save():

    class Command(BaseCommand):
        def populate_db(self):
            zip_code_object = ZipCode(zip_code='10566', latitude = 10.2, longitude= 43.4) #test data to see if I could get it working
            zip_code_object.save()
    
        def handle(self, *args, **options):
            self.populate_db()