Django:使用外键创建链接表

发布于 2024-12-10 10:09:53 字数 507 浏览 1 评论 0原文

我的 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 技术交流群。

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

发布评论

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

评论(1

绝情姑娘 2024-12-17 10:09:53

这更接近你想要的。

def adduser(request):
    u = User(email=request.POST['email'], username=request.POST['username'], password=request.POST['password'])
    u.save()
    a = Accounts(
        user=u
    )
    a.save()
  1. 你使用 django 的 User 模型吗?

如果是这样,您实际上想要这个:

def adduser(request):
    u = User(email=request.POST['email'], username=request.POST['username'])
    u.set_password(request.POST['password'])
    u.save()
    a = Accounts(
        user=u
    )
    a.save()

另外,您是否考虑过使用 django 的表单和表单实用程序,而不是到处使用 request.POST 变量?他们很好。

This is much closer to what you want.

def adduser(request):
    u = User(email=request.POST['email'], username=request.POST['username'], password=request.POST['password'])
    u.save()
    a = Accounts(
        user=u
    )
    a.save()
  1. Are you using django's User model?

if so you actually want this:

def adduser(request):
    u = User(email=request.POST['email'], username=request.POST['username'])
    u.set_password(request.POST['password'])
    u.save()
    a = Accounts(
        user=u
    )
    a.save()

Also, rather than using request.POST variables everywhere, have you considered using django's forms and form utilities? They're quite nice.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文