你能把模型作为django视图函数的参数传递吗?

时间:2014-07-30 16:39:39

标签: python django

我正在使用django 1.6和postgresql。我有多个具有相似字段的模型,如下所示:

class MU2(models.Model):
    name = models.CharField(max_length=200,default="",unique=True)
    addresses = models.CharField(max_length=200,default="")
    email = models.CharField(max_length=200,default="")
    ......

是否可以将模型名称作为参数传递?在伪代码我想

def savePractices(practices, MODELNAME):

    from ml1.models import MODELNAME

    for practice in practices:
        p =MODELNAME(**practice)
        try:
            p.save()
        except IntegrityError:
            print "error"

    return

4 个答案:

答案 0 :(得分:3)

get_model模块中的

django.db.models.loading是您正在寻找的内容:

from django.db.models.loading import get_model

def savePractices(practices, model_name):

    model = get_model('YOUR_APP_NAME', model_name)

    (...)

答案 1 :(得分:2)

这样做可能会更好:

class ModelMix(object):

    @classmethod
    def savePractices(cls, practices):
        for practice in practices:
            p = cls(**practice)
            try:
                p.save()
            except IntegrityError:
                print "error"

        return


class MU1(models.Model, ModelMix):
    name = models.CharField(max_length=200,default="",unique=True)
    addresses = models.CharField(max_length=200,default="")
    email = models.CharField(max_length=200,default="")

class MU2(models.Model, ModelMix):
    name = models.CharField(max_length=200,default="",unique=True)
    addresses = models.CharField(max_length=200,default="")
    email = models.CharField(max_length=200,default="")

MU1.savePractices(practices)
MU2.savePractices(practices)

答案 2 :(得分:1)

您可以使用__import__importlib动态加载模块。

它将从modulename加载模块。

答案 3 :(得分:1)

您甚至可以执行以下操作:

def savePractices(practices, MODELNAME):

    from ml1 import models

    dynamic_model = getattr(models, MODELNAME)
    for practice in practices:
        p = dynamic_model(**practice)
        try:
            p.save()
        except IntegrityError:
            print "error"

    return