Django,Python,尝试更改从数据库对象检索的对象中的字段值/属性。所有调用,不起作用

发布于 2024-09-19 06:35:55 字数 433 浏览 7 评论 0原文

我正在尝试更改从 django db 调用检索到的对象中的字段中的特定字段。

class Dbobject ()
   def __init__(self):
       dbobject = Modelname.objects.all()
   def test (self):
       self.dbobject[0].fieldname = 'some new value'

然后我可以像这样访问特定属性:

objclass = Dbobject()
fieldvalue = dbobject.dbobject[0].fieldname

但我希望能够使用 Dbobject 类的“test”方法来尝试更改对象属性值的特定值,但它并没有改变它。我对此感到困惑,因为这就是我认为应该更改对象属性值的方式。

I'm trying to change a specific field from a field in an object that I retrieved from a django db call.

class Dbobject ()
   def __init__(self):
       dbobject = Modelname.objects.all()
   def test (self):
       self.dbobject[0].fieldname = 'some new value'

then I am able to access a specific attribute like so:

objclass = Dbobject()
fieldvalue = dbobject.dbobject[0].fieldname

but I want to be able to use the "test" method of the Dbobject class to try to change the specific value on an object's attribute value, but it isn't changing it. I am stumped by this as this is how I thought I am supposed to change an object's attribute value.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

月依秋水 2024-09-26 06:35:55

我不确定这是否是问题所在,但我认为您可能缺少 save() 方法。

from models import Person
p = Person.objects.get(pk=100)
p.name = 'Rico'
p.save()      # <== This writes it to the db. Is this what you're missing?

以上是简单的情况。根据您上面所写的内容进行调整,它会像:

dbobject.dbobject[0].fieldname = 'some new value'
dbobject.dbobject[0].save()

或者,我会写得更像:

rec = dbobject.dbobject[0]
rec.fieldname = 'some new value'
rec.save()

另请注意,根据您是否以及如何使用事务,您可能会也可能不会看到数据库的更改,直到您提交。

I'm not sure if this is the problem or not, but I think you might be missing a save() method.

from models import Person
p = Person.objects.get(pk=100)
p.name = 'Rico'
p.save()      # <== This writes it to the db. Is this what you're missing?

Above is the simple case. Adapted for what you wrote above, it'd be like:

dbobject.dbobject[0].fieldname = 'some new value'
dbobject.dbobject[0].save()

or, I'd write it more like:

rec = dbobject.dbobject[0]
rec.fieldname = 'some new value'
rec.save()

Also note that depending on whether and how you are using transactions, you may or may not see a change to the database until you commit.

妞丶爷亲个 2024-09-26 06:35:55

我不完全确定你想要实现什么,但它不应该是这样的:

class Dbobject ():
   def __init__(self):
       self.dbobject = Modelname.objects.all()
   def test (self):
       self.dbobject[0].fieldname = 'some new value'

I am not totally sure what you are trying to achieve, but shouldn't it be something like:

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