【发布时间】:2017-11-27 09:54:32
【问题描述】:
我正在为我的博客网站构建 LIKE、UNLIKE 和 CLAPPING 功能。我有这样的模型: 模型反应(喜欢、不喜欢和鼓掌)
class Reaction(models.Model):
REACT_TYPES = (
(LIKE, 'Like'),
(CLAPPING, 'Clapping')
)
user = models.ForeignKey(User)
react_type = models.CharField(max_length=100, choices=REACT_TYPES, default='LIKE')
timestamp = models.DateTimeField(auto_now_add=True, null=True)
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, null=True)
object_id = models.PositiveIntegerField(null=True)
content_object = GenericForeignKey('content_type', 'object_id')
class Meta:
unique_together = ('user', 'content_type', 'object_id')
序列化器模型 REACTION 从模型导入反应
class ReactCreateUpdateSerializer(ModelSerializer):
class Meta:
model = Reaction
fields = [
'user',
'react_type',
'content_type',
'object_id',
]
我的 REACT 视图集:
from rest_framework.generics import CreateAPIView
class ReactCreateAPIView(CreateAPIView):
queryset = Reaction.objects.all()
serializer_class = ReactCreateUpdateSerializer
我假设之前创建了一个带有 LIKE 的对象。我想构建一个函数可以做这些事情:
- 如果用户再次使用存在 4 个对象的 POST 方法:
user, content_type, object_id, react_type=LIKE。它成为删除对象。 (不喜欢)。然后,如果再发布一个,它将再次成为创建对象。 (喜欢) - 如果用户使用存在 4 个对象的 POST 方法:
user, content_type, object_id, react_type=CLAPPING。它变为使用更新 2 字段更新数据库中的可用反应:react_type 和时间戳,所有其他字段均未更改。
我认为这是每个人在为网站构建 API 需要反应时都会遇到的问题。所以希望您的热心帮助。提前致谢!
【问题讨论】:
-
无需删除记录,如果该用户已经喜欢,您只需更新其
react_type= UNLIKE。 -
我可以更新 models.py 或 serializers.py 中的 def 吗?有没有一个例子@Satendra
标签: django django-models django-rest-framework