Python 使用现有模型在django中创建多对一关系
如何在django中创建与现有模型的多对一关系?查看,您可以看到可以创建一个外键,并使用对另一个模型的引用创建and对象 比如说,Python 使用现有模型在django中创建多对一关系,python,django,foreign-keys,Python,Django,Foreign Keys,如何在django中创建与现有模型的多对一关系?查看,您可以看到可以创建一个外键,并使用对另一个模型的引用创建and对象 比如说, 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 = 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()
然后,您可以使用a.reporter.id
访问r
的id
但是,这样做的一个问题是,如果要通过a
检查r
的id,必须创建a
对于已经存在的模型,您将如何做到这一点
例如,如果我有一个用户,并且我希望该用户能够为游戏创建多个角色,那么如果该用户已经存在,我如何为该角色分配外键
看看,您会发现您需要给出想要引用外键的模型,但它实际上并没有解释如何做
对于已经存在的模型,您将如何做到这一点
不清楚你指的是哪种型号。如果你是指现有的记者,你会得到它,并以完全相同的方式:
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')
如果我有一个AbstractUser,我该怎么做?我得到一个错误,上面写着:
字段定义了与模型“auth.User”的关系,该模型已被调出。
读取异常并遵循其建议。在这种情况下,不要定义与auth.User的关系!