[Answered ]-Is there a way to identify when a 'like' was put on a blog post?

1👍

Not with a ManyToMany without a through model no. But nothing stops us from making one. Indeed:

class Post(models.Model):
    objects = PostManager()
    author = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.SET_NULL,
        default=None,
        null=True,
    )
    title = models.CharField(max_length=100)
    description = models.TextField(max_length=500)
    date = models.DateTimeField(auto_now_add=True)
    likes = models.ManyToManyField(
        settings.AUTH_USER_MODEL,
        related_name='post_like',
        blank=True,
        through='PostLike',
    )


class PostLike(models.Model):
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    liker = models.ForeignKey(Post, on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)

We can then get the PostLikes of a Post with:

from django.db.models import Prefetch

posts = Post.objects.prefetch_related(
    Prefetch('postlike_set', PostLike.objects.select_related('liker'))
)

for post in posts:
    for postlike in post.postlike_set.all():
        print(f'like for {post} by {postlike.liker} on {postlike.created_at}')

Leave a comment