我正在尝试运行一次性管理命令来预填充数据库。
这是模型:
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)
这是管理命令:
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()
但是当我运行python3.6 manage.py populate_zip_code_db
它返回
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'
有谁知道如何让它工作?我刚刚发现了管理命令,所以我一无所知。
而不是
ZipCode.save(self)
它应该是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()