我正在使用 object.create 将记录存储到 django 数据库:
result = MyObject.objects.create(var1='foo',
var2='bar',
...
)
执行后result
是 __str__
返回的任何字符串(我通过将其更改为 return self.id
来确认这一点)。我希望能够访问主键值,因为在某些情况下下一步是创建另一条记录,通过外键引用该记录,但我真的很喜欢 __str__
返回比这更有意义的东西。
我意识到我可以获取最近创建的,但这将是具有多个并发用户的线程代码,因此有可能以真正不幸的方式失败。
我正在使用 SQLite 数据库进行开发,但将切换到 MySQL 进行生产,因此,如果有办法解决需要 mySQL 的问题,我现在就可以进行切换。
更新 - 没关系
好吧,我知道发生了什么了。第一次通过时,不会发生对 create 的调用,而 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'
关于python - 我可以让 Django 在创建时返回记录的 ID 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19529418/