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)
No. Remove
linksfrom the Bookmark model, and to access the Link objects for a specific Bookmark you will usebookmark.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
bookmarkForeignKey, such as “links” if you do not like “link_set”.