如何通过字符串引用模型列?

时间:2018-01-20 21:07:12

标签: django django-models

我正在制作一个终端命令,用户输入两个字符串。一个对应于模型,另一个对应于该模型的列。

class Command(BaseCommand):
    def add_arguments(self, parser):
        parser.add_argument(
            "--model",
            dest="model",
            required=True,
        )
    def add_arguments(self, parser):
        parser.add_argument(
            "--col",
            dest="col",
            required=True,
        )
def handle(self, *args, **options):
    # Handle stuff here

我知道我可以执行from django.apps import apps并将options["model"]放在apps.get_model()中以获取用户输入的模型实例(假设它存在)。但是如何引用用户在options["col"]中输入的列?

1 个答案:

答案 0 :(得分:1)

首先,您应该删除重复的add_argument方法。其次,您应该要求app的名称,因为如果两个不同的应用程序共享相同的型号名称会发生​​什么?如果这些同名模型共享相同的字段名称会怎样。该命令应该在哪个列上应用?

这是一个工作命令(也接受app参数):

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.