Django:如何通过id获取模型实例
我需要传递一个模型实例来创建另一个带有外键的模型实例。我有条目 ID,但如果我这样做,
user = User.objects.get(id = request.user.id)
但是出来的这个“用户”东西不是模型“实例”,当我将它作为外键引用传递到另一个模型时,我会收到错误。
我应该在这里做什么?这似乎是一个棘手的问题......如果您有一个带有外键的模型,要创建该模型的新实例,您需要相应外键模型的新实例。但是,如果该外键模型在数据库中已有记录怎么办?如果objects.get() 不会给你一个“实例”,你能做什么?您无法在数据库中创建另一个新实例 - 这是错误的,并且不起作用,因为 id 都是自动递增的。
我一定在这里错过了一些大事......
I need to pass a model instance to create another model instance with a foreign key. I have the entry id, but if I do,
user = User.objects.get(id = request.user.id)
But this "user" thing that comes out isn't a model "instance", and when I pass it into another model as a foreign key reference I get an error.
What should I do here? This seems like a intractable problem... If you have a model with a foreign key, to create a new instance of that model you need a fresh instance of the corresponding foreign-key model. But what if that foreign-key model already has a record in the database? If the objects.get() won't give you an "instance", what can you do? You can't exactly create another new instance in the database - which is just wrong, and won't work since the id's are all auto-incremented anyway.
I must be missing something big here....
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论