我正在为我的Django应用程序制作一个终端命令:
from django.core.management.base import BaseCommand, CommandError
from django.core.exceptions import FieldDoesNotExist
from django.apps import apps
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument(
"--app",
dest="app",
required=True,
)
parser.add_argument(
"--model",
dest="model",
required=True,
)
parser.add_argument(
"--col",
dest="col",
required=True,
)
def handle(self, *args, **options):
app_label = options.get('app')
model_name = options.get('model')
column_name = options.get('col')
try:
model = apps.get_model(app_label=app_label, model_name=model_name)
except LookupError as e:
msg = 'The model "%s" under the app "%s" does not exist!' \
% (model_name, app_label)
raise CommandError(msg)
try:
column = model._meta.get_field(column_name)
except FieldDoesNotExist as e:
msg = 'The column "%s" does not match!' % column_name
raise CommandError(msg)
else:
print(column, type(column))
# Do stuff here with the column, model.
目前,column
为<django.db.models.fields.IntegerField: column_name>
。我希望model
的此实例将column_name
设置为100
。如何以这种方式设置和保存此实例?
答案 0 :(得分:1)
实际上,您需要首先根据过滤器或ID检索模型的实例,例如
model_instance = model.objects.get(pk=1)
您显然需要先确定要更新的实例。
然后您可以在实例
上执行以下操作setattr(model_instance, 'column_name', 100)
这会将值100设置为属性名称&#39; column_name&#39;到模型实例。
然后您可以运行model_instance.save()
,如果需要,可以将值保存到数据库中。
如果要创建新的模型实例,您可以执行以下任一操作:
model_instance = model(column_name=100)
或
model_instance = model()
setattr(model_instance, column_name, 100)
其次是
model_instance.save()