Best way to make “viewed” attribute for messages i

2019-08-23 06:17发布

I am deciding on how to track if a user has seen a post in the timeline or not.

There is Post and Comment model like this.

class Comment(models.Model):
    author = models.ForeignKey('UserProfile')
    title = models.CharField(max_length=255)
    text = models.TextField(null=True, blank=True)
    date_created = models.DateTimeField()

    post = models.ForeignKey('Post', related_name='comments')

class Post(ContentTypeModel):
    title = models.CharField(max_length=255)
    group = models.ForeignKey('UserGroup', null=True)

    date_updated = models.DateTimeField()

Suggestions about best practices on how to track if post has been seen by particular member of a user group will be nice.

1条回答
唯我独甜
2楼-- · 2019-08-23 07:02

I managed to do as was suggested, i.e. adding m2m relation to track who viewed the post:

class Post(models.Model):
    ...
    date_updated = models.DateTimeField()
    viewers = models.ManyToManyField('UserProfile', through='PostViewer')

class PostViewer(models.Model):
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    viewer = models.ForeignKey('UserProfile', on_delete=models.CASCADE, related_name='posts_seen')

    last_seen = models.DateTimeField(null=True, blank=True, help_text='Is set when user sees the post in details')

    class Meta:
        unique_together = ('post', 'viewer')

This way i can compare post.date_updated to viewer.last_seen and get desired filtering on who have seen the update/create of Post.

查看更多
登录 后发表回答