我为我的博客网站建立了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')
Serializers模型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可用的对象。我想构建一个函数可以做这些事情:
user, content_type, object_id, react_type=LIKE
。它变成删除对象。 (不同于)。然后如果再发一个,它就会再次创建对象。 (像)user, content_type, object_id, react_type=CLAPPING
。它将使用更新2字段更新数据库中的可用响应:react_type和timestamp,所有其他字段未更改。我认为,当他为网站需求反应构建API时,每个人都会遇到问题。希望你的热情帮助。提前致谢!
答案 0 :(得分:1)
您只需要在请求数据中发送react_type
,
如果你创建一个 @detail_route object_id
,那么pk
将始终存在,如果用户是user
对象将在请求中可用以 request.user
任何用户的反应对象都将在该用户提出的第一个请求时创建。
无需删除记录,如果用户已经react_type=UNLIKE
,则必须更新反应对象LIKED
。
class PostViewSet(viewsets.ModelViewSet):
# Data model on which user is reacting
queryset = Post.objects.all()
serializer_class = PostSerializer
@detail_route(methods=['post'])
def react(self, request, pk=None):
react_type = request.data['react_type']
obj = self.get_object()
# GenericForeignKey does not support get_or_create
try:
reaction_obj = Reaction.objects.get(content_type=ContentType.objects.get_for_model(obj), object_id=obj.id, user=request.user)
reaction_obj.react_type = react_type
reaction_obj.save()
except Reaction.DoesNotExist:
obj.reactions.create(user=request.user, react_type=react_type)
return Response({'success': True})
用户响应的模型应该具有多态连接
class Post(models.Model)
# Other fields
...
reactions = GenericRelation(Reaction, related_query_name='posts')
将您的视图注册为
url(r'^posts/(?P<pk>[0-9]+)/$', PostViewSet.as_view(), name='post-reaction')
# http://domian.com/api/v1/posts/1/react
# method: POST
# data : {'react_type': 'UNLIKE'}
# content-type: 'application/json'