Creating a “like” url/button for Django Rest Frame

2019-09-09 02:50发布

问题:

I'm working on an API to use for an iPhone app. In order to like a picture, I'm assuming I need to embed a url in my serializer that can be used to add a like to a photo. Could someone please help me implement this?

I am able to view the url, but I'm not sure how to pass the photo's id to the view. This is where I've gotten so far:

views.py:

@api_view(['POST'])
def like_create_api(request, photo_id):
    serializer = PhotoSerializer(data=request.DATA)
    if serializer.is_valid():
        serializer.object.content_object = get_object_or_404(Photo, id=photo_id)
        serializer.object.likers.add(request.user)
        serializer.save()
        return RestResponse(serializer.data, status=status.HTTP_201_CREATED)
    return RestResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

serializers.py:

class PhotoSerializer(serializers.ModelSerializer):
    likers = serializers.HyperlinkedRelatedField(
        many=True, view_name='user_account_detail_api', read_only=True,
        lookup_field='username')
    like_url = LikeUrlField("like_create_api")

    class Meta:
        model = Photo
        fields = ['like_url', 'id', 'slug', 'photo', 'likers']

models.py:

class Photo(HashtagMixin, TimeStampedModel):
    category = models.ForeignKey("Category")
    creator = models.ForeignKey(settings.AUTH_USER_MODEL)
    likers = models.ManyToManyField(settings.AUTH_USER_MODEL,
                                    related_name='likers', blank=True)
    photo = models.ImageField(upload_to=upload_location)
    slug = models.SlugField()

    class Meta:
        app_label = 'photos'

    def __unicode__(self):
        return u"{}".format(self.slug)

urls.py:

url(r'^like/$', 'api.views.like_create_api',
        name='like_create_api'),

Any help is appreciated. Thank you in advance!

回答1:

You don't need to use a serializer for validation just save the like relation.

@api_view(['POST'])
def like_create_api(request, photo_id):
    photo = get_object_or_404(pk=photo_id)
    photo.likers.add(request.user)
    serializer = PhotoSerializer(photo)
    return Response(serializer.data, status=status.HTTP_201_CREATED)


回答2:

Did you mean (?P<photo_id>\d+)/$ in url?

Something like this:

url(r'^like/(?P<photo_id>\d+)/$', 'api.views.like_create_api',
    name='like_create_api'),

UP: If you need to fetch post form parameter (request.POST.get('photo_id', '')) then your view must be like this:

@api_view(['POST'])
def like_create_api(request):
    ...
        serializer.object.content_object = get_object_or_404(Photo,
            id=request.POST.get('photo_id', ''))
    ...