我正在使用object.create将记录存储到Django数据库中:

     result = MyObject.objects.create(var1='foo',
                                      var2='bar',
                                         ...
                                     )


执行此命令后,result就是__str__返回的任何字符串(我将其更改为return self.id确认了此字符串)。我想访问主键值,因为在某些情况下,下一步是创建另一条记录,该记录通过外键引用该记录,但是我真的很想__str__返回比这更有意义的东西。

我意识到我可以抓住最近创建的代码,但这将是具有多个并发用户的线程代码,因此有可能以真正不幸的方式失败。

我正在使用SQLite数据库进行开发,但是将切换到MySQL进行生产,因此,如果有解决此问题的方法需要mySQL,我现在可以进行切换。

更新-没关系

好吧,我知道发生了什么事。第一次进行创建调用不会发生,并且在result定义时它不是对象。

谢谢大家进一步挖掘以回应您的评论是促使我找到它的原因。

最佳答案

# No reporters are in the system yet.
>>> Reporter.objects.all()
[]

# Create a new Reporter.
>>> r = Reporter(full_name='John Smith')

# Save the object into the database. You have to call save() explicitly.
>>> r.save()

# Now it has an ID.
>>> r.id
1

# Now the new reporter is in the database.
>>> Reporter.objects.all()
[<Reporter: John Smith>]

# Fields are represented as attributes on the Python object.
>>> r.full_name
'John Smith'


另请参阅:https://docs.djangoproject.com/en/1.5/intro/overview/

10-07 13:06
查看更多