[Answer]-Django Many-to-Many Relation or One-to-Many relation

1๐Ÿ‘

โœ…

You just need to think about how photos are liked.

Can a user like many photos?

Can many photos be liked by the one user?

Then it is a many to many.

You would implement it like this

class Photo(models.Model):
    publish_by = models.ForeignKey(User)
    name = models.CharField(max_length=40)
    desc = models.CharField(max_length=40)
    liked_by = models.ManyToManyField(User, related_name="likes")

Then, it works like this, you can add likes to a photo by

photoInstance.liked_by.add(user)

Access the likes of a photo this way

 photoInstance.liked_by.all()

To get all the photos a user liked

user.likes.all()
๐Ÿ‘คZe'ev G

0๐Ÿ‘

class Like(models.Model):
    user = models.ForeignKey(User)
    photo  = models.ForeignKey(Photo)
๐Ÿ‘คDenis

Leave a comment