基于Django框架利用Ajax实现点赞功能实例代码-创新互联
概要:

要实现点赞功能,需要实现的有:谁进行的点赞、什么时候进行点赞、点赞的对象是谁、每一个对象的点赞数量是多少、点赞过后还需要能够取消点赞,为了是点赞后的信息能够及时的显示在前端页面,就需要使用Ajax来异步请求数据,实现实时显示。
下面话不多说了,来随着小编一起看看详细的介绍吧
模型分析:
创建的模型需要记录的数据有:点赞者、点赞对象、点赞时间、点赞的数量,由于前面三个属性主要用于记录点赞的状态,而点赞数量主要用于记录某篇文章的点赞数量,所以这里最好把点赞数量单独放在一个模型中。这里就创建了两个模型,LikeRecord和LIkeCount,LikeRecord用于记录点赞状态,LIkeCount用于记录点赞的数量。大致的思路图:
代码:
from django.db import models
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.contrib.auth.models import User
# Create your models here.
# 用于记录点赞数量的模型
class LikeCount(models.Model):
content_type = models.ForeignKey(ContentType, on_delete=models.DO_NOTHING)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
# 用于记录点赞数量的字段
like_num = models.IntegerField(default=0)
# 用于记录点赞状态的模型
class LikeRecord(models.Model):
content_type=models.ForeignKey(ContentType, on_delete=models.DO_NOTHING)
object_id=models.PositiveIntegerField()
content_object=GenericForeignKey('content_type', 'object_id')
# 记录点赞的用户
like_user = models.ForeignKey(User, on_delete=models.DO_NOTHING)
# 记录点赞的时间
like_time = models.DateTimeField(auto_now_add=True) 网页题目:基于Django框架利用Ajax实现点赞功能实例代码-创新互联
本文URL:http://www.scyingshan.cn/article/cshepo.html


咨询
建站咨询
