Home > other >  Trying to Implement simple API in Django
Trying to Implement simple API in Django

Time:02-16

I am very new to Django and trying to implement small API for social media website where I can monitor if post has been liked and number of likes and later fetch API using JavaScript so I can like without refreshing the page using put method. Problem is that I largely failed because of lack of proper knowledge. I could not get the API working in the first place.

models.py

from django.contrib.auth.models import AbstractUser
from django.db import models

class User(AbstractUser):
    pass

class New_Post(models.Model):
    user = models.ForeignKey(User, null=True, on_delete=models.CASCADE)
    New_Post =  models.CharField(null=True, max_length=300)
    def __str__(self):
        return f"{self.New_Post}"

class Likes(models.Model):
    user = models.ForeignKey(User, null=True, on_delete=models.CASCADE)
    like = models.BooleanField(default=False)
    New_Post =  models.ForeignKey(New_Post, null=True, on_delete=models.CASCADE)
    def serialize(self):
        return {
        "id": self.id,
        "post": self.New_Post,
        "user": self.user,
        "like": self.like
    }

views.py fragment

def likes(request):
    like = Likes.objects.all()
    return JsonResponse(like.serialize())

urls.py

urlpatterns = [
    path("", views.index, name="index"),
    path("login", views.login_view, name="login"),
    path("logout", views.logout_view, name="logout"),
    path("register", views.register, name="register"),
    path("Post", views.likes, name="likes"),
]

When I try to access Post url I expect json response to be shown on mostly blank page. Should it be like that? How can I get my API working?

CodePudding user response:

The serialize method handles one Like object while like is an a list of likes, which doesn't have such a function

One technique is to loop on the objs inside

def likes(request):
    likes = [l.serialize() for l in Likes.objects.all()]
    return JsonResponse(likes,safe=False)

safe is False as JSONResponse wants an object by default.

  • Related