Python,Django,如何使用getattr(或其他方法)调用具有多个属性的对象?
在尝试让它工作一段时间并四处搜索后,我真的很困惑,所以在这里发帖...我想在我为 django 编写的类中创建一些函数尽可能通用,所以我想使用 getattr 来调用诸如下面的函数以通用方式:
我的工作方式(非通用方式):
from django.db.models import get_model
mymodel = get_model('appname', 'modelname')
dbobject = mymodel.objects.all()
我的尝试之一以通用方式创建它,仍然不起作用,它确实返回了一些东西,但它不是正确的对象类型,以便我可以从中获取数据(它是 django 的数据库调用)
ret = getattr(mymodel,'objects')
dbobject = getattr(ret,'all')
After trying to get this to work for a while and searching around I am truly stumped so am posting here... I want to make some functions in classes that I am writing for django as generic as possible so I want to use getattr to call functions such as the one below in a generic manner:
the way I do it that works (non-generic manner):
from django.db.models import get_model
mymodel = get_model('appname', 'modelname')
dbobject = mymodel.objects.all()
one of my attempts create this in a generic manner, still not working, it does return something back but its not the proper object type so that i can get the data from it (its a database call for django)
ret = getattr(mymodel,'objects')
dbobject = getattr(ret,'all')
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您忘记调用结果了。
访问方法
mymodel.objects.all
并调用它。访问方法
mymodel.objects.all
但不调用它。您所需要做的就是将最后一行更改为:
You forgot to call the result.
Accesses the method
mymodel.objects.all
and then calls it.accesses the method
mymodel.objects.all
but does not call it.All you need is to change the last line to:
如果它是一个函数,您将需要调用该属性,例如
You will need to call the attribute if it's a function, e.g.