我正在尝试运行一次性管理命令来预填充数据库。
这是模型:
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'
有人知道如何使它工作吗?我只是发现了管理命令,所以一无所知。
答案 0 :(得分:0)
应改为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()