Django:使用外键创建链接表
我的 SQLite 数据库中有 3 个表:用户、帐户、密码。帐户和密码的 id 是 User.id 的外键。问题是 User 的实例在保存之前没有 id(并且 django 添加了主字段)。这就是我尝试执行此操作的方式,因为 User.email 应该是唯一的,那么我应该只取回一个对象,但它不起作用。我确信有更好的方法来做到这一点。
tl;dr 当我创建用户时,我还想为他们创建一个帐户和密码表,通过外键 id 链接,这也是主键。
def adduser(request):
u = User(email=request.POST['email'], username=request.POST['username'], password=request.POST['password'])
a = Accounts()
u.save()
u = User.objects.get(email=request.POST['email'])
a.id = u.id
a.save()
I have 3 tables in my SQLite database: User, Accounts, Passwords. The id of the Accounts and Passwords is a ForeignKey to User.id. The problem is that an instance of User doesn't have an id until it is saved (and django adds the Primary Field). This is how I am trying to do it, since the User.email should be unique then I should only get back one object but it isn't working. I'm sure there is a better way to do this.
tl;dr When I create a User, I also want an Accounts and Passwords table created for them, linked via a ForeignKey, id, which is also the PrimaryKey.
def adduser(request):
u = User(email=request.POST['email'], username=request.POST['username'], password=request.POST['password'])
a = Accounts()
u.save()
u = User.objects.get(email=request.POST['email'])
a.id = u.id
a.save()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这更接近你想要的。
如果是这样,您实际上想要这个:
另外,您是否考虑过使用 django 的表单和表单实用程序,而不是到处使用 request.POST 变量?他们很好。
This is much closer to what you want.
if so you actually want this:
Also, rather than using request.POST variables everywhere, have you considered using django's forms and form utilities? They're quite nice.