Reputation: 420
How can I create a many to one relationship with an existing model in django? Looking at the documentation, You can see that you can create a foreign key and create and object with a reference to the other model.
For example,
r = Reporter(first_name='John', last_name='Smith', email='[email protected]')
r.save()
a = Article(id=None, headline="This is a test", pub_date=date(2005, 7, 27), reporter=r)
a.save()
You can then access the id of r
with a.reporter.id
.
One problem with this, however is that if you wanted to check the id of r
through a
, you have to create a
in order to do it.
How would you do this with an already existing model?
As an example, if I have a user and I want the user to be able to create multiple characters for a game, how can I assign the character a foreign key to the user if the user already exists?
Looking at this answer, you see that you need to give the model that you want to reference to the foreign key, but it doesn't actually explain how to do it.
Upvotes: 0
Views: 586
Reputation: 10794
How would you do this with an already existing model?
It's unclear which model you're referring to. If you mean an existing reporter, you'd get it and do it exactly the same way:
r = Reporter.objects.get(email='[email protected]')
a = Article(headline="This is a test", pub_date=date(2005, 7, 27), reporter=r)
a.save()
If you mean an existing article, you can change the foreign key just like any model instance field:
a = Article.objects.get(headline="This is a test")
a.r = Reporter.objects.create(...) # or .get() depending on what you want.
a.save()
How can I assign the character a foreign key to the user if the user already exists?
Using the same logic, you'd get the user and create a new character with this existing user object:
# 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')
Upvotes: 1