Creating many-to-many relationships

We will add another field to the Image model to store the users who like an image. We will need a many-to-many relationship in this case because a user might like multiple images and each image can be liked by multiple users.

Add the following field to the Image model:

users_like = models.ManyToManyField(settings.AUTH_USER_MODEL,                                    related_name='images_liked',                                    blank=True)

When you define a ManyToManyField, Django creates an intermediary join table using the primary keys of both models. The ManyToManyField can be defined in any of the two related models.

As with ForeignKey fields, the related_name attribute of ManyToManyField allows us to name the relationship from the related object back to this one. The  ...

Get Django 2 by Example now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.