如何在django中创建与现有模型的多对一关系?查看the documentation,您可以看到可以创建外键并使用对其他模型的引用来创建和对象。
例如,
r = Reporter(first_name='John', last_name='Smith', email='john@example.com')
r.save()
a = Article(id=None, headline="This is a test", pub_date=date(2005, 7, 27), reporter=r)
a.save()
然后,您可以使用r
访问a.reporter.id
的ID。
但有一个问题是,如果您要检查r
到a
的ID,则必须创建a
才能执行此操作。
您如何使用现有模型执行此操作?
例如,如果我有一个用户,并且我希望用户能够为游戏创建多个角色,如果用户已经存在,如何为用户分配一个外键?
查看this answer,您会发现需要提供要引用外键的模型,但实际上并没有解释如何执行此操作。
答案 0 :(得分:1)
您如何使用现有模型执行此操作?
目前还不清楚你指的是哪种型号。如果你的意思是现有的记者,你就会得到它并以同样的方式完成:
r = Reporter.objects.get(email='john@example.com')
a = Article(headline="This is a test", pub_date=date(2005, 7, 27), reporter=r)
a.save()
如果您指的是现有文章,则可以像更改模型实例字段一样更改外键:
a = Article.objects.get(headline="This is a test")
a.r = Reporter.objects.create(...) # or .get() depending on what you want.
a.save()
如果用户已经存在,如何为用户分配外键?
使用相同的逻辑,您将获得用户并使用此现有用户对象创建一个新角色:
# Get user, or if this was the logged in user maybe just request.user
user = User.objects.get(username='wanderer')
# Create the character, using the existing user as a foreign key
# (the .create is just shorthand for creating the object then saving it)
Character.objects.create(character_name='Trogdor', user=user)
# Or alternatively, you can simply use the implicit reverse relationship
user.character_set.create(character_name='Homestar Runner')