我有 10 个模型类,我想检查传递的数据是否在表中可用。我有一个计划,我可以创建一个函数,该函数将采用模型类名称、要检查的属性和该字段的值作为参数。 来自数据导入模型
def IsAvailable(model, attr, val):
# Here I wanted to create object of given model class and validate whether the attr has the give value.
obj = getattr(models, model)
res = obj.objects.get(attr=val)
return res
这将不起作用,因为 attr 不是给定模型中的字段。有人可以帮我吗?
请您参考如下方法:
你可能想要 ** keyword pass-through :
def IsAvailable(model, attr, val):
obj = getattr(models, model)
res = obj.objects.get(**{attr: val})
return res
这会将字典 {attr: val}< 作为关键字参数传递给 get(),即 {'foo': 'bar'} 调用 get(foo='bar'}。
制作这个通用的奖励积分:
def IsAvailable(model, **kwargs):
obj = getattr(models, model)
res = obj.objects.get(**kwargs)
return res
这让您可以调用 IsAvailable(model, attr1=val1, attr2=val2),测试所有属性的可用性,这可能会更方便。
在 Django 1.7 中,您还可以跨应用程序按名称为整个项目解析模型(在 django < 1.7 中也可以,但使用 a different method )。
from django.apps import apps
def get_model_dotted(dotted_model_name):
app_label, model_name = dotted_model_name.split(".", 1)
return apps.get_model(app_label, model_name)
def IsAvailable(model, **kwargs):
model = get_model_dotted(model_name)
res = model.objects.get(**kwargs)
return res;
用作 IsAvailable('app1.model1', attr1=value1)。
记住 get() 引发了 MultipleObjectsReturned当不止一个对象匹配过滤器时,所以你可能真的想要
res = model.objects.filter(**kwargs)
甚至只是
return model.objects.filter(**kwargs).exists()
