[Answered ]-Django Like mechanism. Database performance question

1๐Ÿ‘

โœ…

I am not sure if this approach creates a new row or uses a different indexing mechanism, but it looks tidier.

A ManyToManyField will create an extra table called a junction table [wiki] with ForeignKeys to the model where you define the ManyToManyField, and the model that you target with the ManyToManyField.

You furthermore only need one ManyToManyField, otherwise you make two relations that act indepdently. You thus model this as:

from django.conf import settings

class Post(models.Model):
    # ... 
    likes = models.ManyToManyField(
        settings.AUTH_USER_MODEL,
        related_name='liked_posts'
    )

class CustomUser(models.Model):
    # ... 
    # no ManyToManyField to Post

Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.

Leave a comment