可以将模型作为参数传递给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 个回答
1
你可以使用 __import__
或者 importlib
来动态加载模块。
这样的话,它会根据模块的名字来加载相应的模块。
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)
3
你可以在 django.db.models.loading
模块里找到你需要的 get_model
函数:
from django.db.models.loading import get_model
def savePractices(practices, model_name):
model = get_model('YOUR_APP_NAME', model_name)
(...)
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