Django model: many-to-many or many-to-one?

I am just learning django and following the tutorial. I have a link and a bookmark. Unlike the tutorial that I am following, I would like the link to be associated with only one bookmark, but there can be several links to bookmarks. Is this a way to customize 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) 
+4
source share
4 answers

Not. Remove links from the Bookmark model, and to access the Link objects for a specific bookmark, you will use bookmark.link_set.all() (where the bookmark is a specific Bookmark object). Django fills the feedback for you.

Or, if you decide so, include your sister name in bookmark ForeignKey, for example, "links" if you don't like "link_set".

+6
source

This is enough to determine the relationship in one of the models. Django will automatically create an attribute in another model.

If you want the link to be associated with only one bookmark, specify the foreign key in Link , which refers to the 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 bookmark links, use bookmark.link_set . This attribute is automatically generated by Django.

+4
source

No, remove the links = operator from Bookmark - what is predefined for you in the bookmark is the link_set property, which is a request for links whose bookmark is this (you can rename this property, but there really is no need for it).

+1
source

if I change the code like this for example: class Bookmark (models.Model): title = models.CharField (max_length = 200)

 class Link(models.Model): url = models.URLField(unique=True) bookmark = models.ForeignKey(Bookmark) 

- the right ratio for them,

+1
source

Source: https://habr.com/ru/post/1307844/


All Articles