RrrangeTop
RrrangeTop

Reputation: 312

Django link multiple tables

I write blog with django. And i have model table Article and i want 'like' it.Should I create new table?(like this)

class LikeArticleUser(models.Model):
class Meta:
    db_table = "likearticleuser"

user = models.ManyToManyField(User)
article_id = models.ManyToManyField(Article)

or maybe

class LikeArticleUser(models.Model):
class Meta:
    db_table = "likearticleuser"

user = models.ForeignKey(User)
article_id = models.ForeignKey(Article)

Upvotes: 0

Views: 2139

Answers (1)

catavaran
catavaran

Reputation: 45575

You have two options:

Use M2M field in the Article model:

class Article(models.Model):
    ...
    liked_by = models.ManyToManyField(User)

Or create the intermediate table by yourself (which is the second snippet in our question):

class LikeArticleUser(models.Model):
    article = models.ForeignKey(Article)
    user = models.ForeignKey(User)

SQL representation for both options will be the same so which option you choose is a matter of taste.

Upvotes: 1

Related Questions