If i am using through table in ManyToMany field what is point of having ManyToManyField?

Hello there,
this is my first question in django forum.
I have two modela Publication and Article as follow.

class Publication(models.Model):
    title = models.CharField(max_length=30)

class Article(models.Model):
    headline = models.CharField(max_length=100)
    publications = models.ManyToManyField(Publication,
                                          related_name="published_article",
                                          through='articles_publication',
                                          through_fields=('article', 'publication'))

In Article model I have ManyToMany publications field which is pointing to the article_publication model which is as follow.

class articles_publication(models.Model):
    articles_publication_id = models.AutoField(primary_key=True, db_column='article_publication_id')
    article = models.ForeignKey(Article, on_delete=models.SET_NULL, null=True)
    publication = models.ForeignKey(Publication, on_delete=models.SET_NULL, null=True)

Now, In this scenario, we are creating an individual model to maintain ManyToMany relation between Article and publication. So, why we should have a field publications in Article Model. Following Article model will perform the same task.

class Article(models.Model):
    headline = models.CharField(max_length=100)

Specifying the ManyToMany field provides any advantage?
Thanks in advance.

1 Like

What you’re getting here is the ability to implicitly join through that intermediate table.

The Many-to-many relationship page documents a lot of the features available that would be lost without it.

For example, when you have the ManyToMany field defined, you can define the relationship using something like a1.publications.add(p1), rather than articles_publication(article=a1, publication=p1)
Also, and perhaps more clear, you can say a1.publications.all() rather than something like Publication.objects.filter(articles_publication__article=a1) (I’m just winging this, I have no idea if this is exactly the right query for this example.)

So yes, I’d say you’re technically correct. I’m not aware of any specific situation where a ManyToManyField is required - in fact, I worked on a system where they were prohibited.
(It was an older version of Django - before 1.6 I believe - it was before the ManyToManyField could specify a ‘through’ table with additional fields. Since we relied heavily on many-to-many relationships with additional data (usually dates tracking when the relationship was applied), we couldn’t use the ManyToManyField in those situations.)

Anyway, so while I don’t believe they’re ever required, they do make writing some queries oh-so-much easier.

3 Likes