Reputation: 969
I'm just learning django and following a tutorial. I have a Link and a Bookmark. Unlike the tutorial I'm following, I would like a link to be associated with only one Bookmark, but a Bookmark can have multiple links. Is this the way to setup the model?
class Link(models.Model):
url = models.URLField(unique=True)
bookmark = models.ForeignKey(Bookmark)
class Bookmark(models.Model):
title = models.CharField(maxlength=200)
user = models.ForeignKey(User)
links = models.ManyToManyField(Link)
Upvotes: 4
Views: 1826
Reputation: 11
if i change the code as this eg: class Bookmark(models.Model): title = models.CharField(max_length=200)
class Link(models.Model):
url = models.URLField(unique=True)
bookmark = models.ForeignKey(Bookmark)
is right relationship for them,
Upvotes: 1
Reputation:
No. Remove links
from the Bookmark model, and to access the Link objects for a specific Bookmark you will use bookmark.link_set.all()
(where bookmark is a specific Bookmark object). Django populates the reverse relationship for you.
Or if you so choose, provide your own related name in the bookmark
ForeignKey, such as "links" if you do not like "link_set".
Upvotes: 5
Reputation: 881635
No, remove the links =
statement from Bookmark
-- what's predefined for you in bookmark is a property link_set
that's the query for the links whose bookmark is this one (you can rename that property, but there's really no need).
Upvotes: 1
Reputation: 137156
It's enough to define the relationship in one of the models. Django will automatically create an attribute in the other model.
If you want a link to be associated with only one bookmark, define a foreign key in Link
that refers back to a Bookmark
object:
class Bookmark(models.Model):
title = models.CharField(max_length=200)
user = models.ForeignKey(User)
class Link(models.Model):
url = models.URLField(unique=True)
bookmark = models.ForeignKey(Bookmark)
To access the links of a bookmark, use bookmark.link_set
. This attribute is automatically created by Django.
Upvotes: 4