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 ManyToManyField fields provide a many-to-many manager that allows us to retrieve related objects, such as image.users_like.all(), or from a user object, such as user.images_liked.all().

Open the command line and run the following command to create an initial migration:

python manage.py makemigrations images

You should see the following output:

Migrations for 'images':
images/migrations/0001_initial.py
- Create model Image

Now, run the following command to apply your migration:

python manage.py migrate images

You will get an output that includes the following line:

Applying images.0001_initial... OK

The Image model is now synced to the database.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset