You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何识别博客文章点赞时间?Django现有模型实现疑问

问题解答

核心结论

你当前的Post模型无法实现按时间段统计获赞最多的文章,必须通过自定义中间模型(也就是你看到的Like模型)来记录每个点赞的时间,才能完成需求。

为什么现有模型不行?

Django的ManyToMany字段默认会生成一张中间表,但这张表只存储post_id和user_id两个关联字段,没有点赞时间的记录。你尝试给likes字段加auto_now_add=True是无效的,因为这个属性是给模型自身的字段用的,和中间表无关——它只会记录Post对象的创建时间,完全追踪不了用户点赞的时间点。

具体解决方案:自定义Like中间模型

你需要创建一个单独的Like模型来存储点赞的时间,然后让Post的likes字段通过这个模型关联用户。

1. 修改模型代码

from django.db import models
from django.conf import settings

class Like(models.Model):
    post = models.ForeignKey('Post', on_delete=models.CASCADE, related_name='like_records')
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)  # 记录点赞时间

    class Meta:
        unique_together = ('post', 'user')  # 避免同一用户重复点赞同一文章

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)
    # 指定用自定义的Like模型作为中间表
    likes = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="post_like", blank=True, through='Like')

2. 点赞操作的修改

自定义中间模型后,不能再用post.likes.add(user)这种默认方式添加点赞了,得通过Like模型来创建记录:

# 给指定文章点赞(先检查是否已点赞,避免重复)
def like_post(post, user):
    if not Like.objects.filter(post=post, user=user).exists():
        Like.objects.create(post=post, user=user)

# 取消点赞
def unlike_post(post, user):
    Like.objects.filter(post=post, user=user).delete()

3. 统计指定时间段的热门文章

比如统计过去7天内获赞最多的文章:

from django.db.models import Count
from django.utils import timezone

# 定义时间范围
start_time = timezone.now() - timezone.timedelta(days=7)

# 统计并排序
top_posts = Post.objects.annotate(
    # 只统计指定时间范围内的点赞数
    recent_like_count=Count('like_records', filter=models.Q(like_records__created_at__gte=start_time))
).order_by('-recent_like_count')

总结

要实现按时间段统计点赞量的需求,必须新建Like模型——没有时间戳的话,根本无法区分点赞发生在哪个时间段,自然做不到精准统计。自定义中间模型后,既能保留原有的点赞关联逻辑,又能新增时间维度的数据,完全满足你的需求。

内容的提问来源于stack exchange,提问作者Callum

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 11:52:56