Python,Django,如何使用getattr(或其他方法)调用具有多个属性的对象?

发布于 2024-09-18 11:26:14 字数 440 浏览 3 评论 0原文

在尝试让它工作一段时间并四处搜索后,我真的很困惑,所以在这里发帖...我想在我为 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

谁把谁当真 2024-09-25 11:26:14

您忘记调用结果了。

dbobject = mymodel.objects.all()

访问方法 mymodel.objects.all 并调用它。

ret = getattr(mymodel,'objects')
self.dbobject = getattr(ret,'all')

访问方法 mymodel.objects.all 但不调用它。

您所需要做的就是将最后一行更改为:

self.dbobject = getattr(ret,'all')()

You forgot to call the result.

dbobject = mymodel.objects.all()

Accesses the method mymodel.objects.all and then calls it.

ret = getattr(mymodel,'objects')
self.dbobject = getattr(ret,'all')

accesses the method mymodel.objects.all but does not call it.

All you need is to change the last line to:

self.dbobject = getattr(ret,'all')()
孤千羽 2024-09-25 11:26:14

如果它是一个函数,您将需要调用该属性,例如

ret = getattr(mymodel,'objects')
all = getattr(ret,'all')
self.dbobject = all()

You will need to call the attribute if it's a function, e.g.

ret = getattr(mymodel,'objects')
all = getattr(ret,'all')
self.dbobject = all()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文