Why am I getting the "Key error" in this code Django Rest Framework?

Well, I am trying to show ads after every 10th post in my feed in Django rest framework with both ad and post model separate. I'm actually stuck and will really appreciate anyone that will help me solve this problem. Here's my code:

My Post & Ad Model

class Post(models.Model):
question = models.TextField(max_length=500)
image = models.ImageField(upload_to='posts/', blank=True, null=True)
category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True)
created_at = models.DateTimeField(auto_now_add=True)
# tags = models.ManyToManyField(Tag, blank=True)
author = models.ForeignKey(User, on_delete=models.CASCADE)
upvote = models.ManyToManyField(User, related_name="like", blank=True)
downvote = models.ManyToManyField(User, related_name="dislike", blank=True)
is_ad = models.BooleanField(default=False)

ordering = ["-created_at"]

def __str__(self):
    return self.question



class Ad(models.Model):
# unique identifier for the ad
id = models.AutoField(primary_key=True)

# name of the ad
name = models.CharField(max_length=255)

# image for the ad
image = models.ImageField(upload_to='ads/images/', blank=True, null=True)

# additional images for the ad
image_2 = models.ImageField(upload_to='ads/images/', blank=True, null=True)
image_3 = models.ImageField(upload_to='ads/images/', blank=True, null=True)
image_4 = models.ImageField(upload_to='ads/images/', blank=True, null=True)
image_5 = models.ImageField(upload_to='ads/images/', blank=True, null=True)

# URL that the ad should redirect to when clicked
url = models.URLField()

# start and end dates for the ad
start_date = models.DateField()
end_date = models.DateField()

# targeting information for the ad
targeting = models.TextField()

# budget for the ad
budget = models.DecimalField(max_digits=10, decimal_places=2)

# ad delivery type (standard or accelerated)
delivery_type = models.CharField(max_length=255)

# ad optimization goal (clicks, impressions, daily unique reach, etc.)
optimization_goal = models.CharField(max_length=255)

# ad placement (desktop, mobile, etc.)
placement = models.CharField(max_length=255)

# ad status (active, paused, deleted)
status = models.CharField(max_length=255)

My Post & Ad Serializer

class AdSerializer(serializers.ModelSerializer):
    class Meta:
       model = Ad
       fields = '__all__'

class PostSerializer(serializers.ModelSerializer):
    class Meta:
       model = Post
       fields = ['id', 'question', 'image', 'category', 'created_at', 'author', 'upvote', 'downvote', 'is_ad']

My Views

 class PostAddListView(generics.ListAPIView):
queryset = Post.objects.all()
serializer_class = PostSerializer

def list(self, request, *args, **kwargs):
    # retrieve the list of posts
    posts = self.get_queryset()

    # initialize the counter variable
    counter = 0

    # create an empty list to store the response
    response = []

    # iterate over the posts
    for post in posts:
        # increment the counter
        counter += 1

        # add the post to the response
        response.append(post)

        # check if the counter is divisible by 10
        if counter % 10 == 0:
            # retrieve a random ad
            ad = Ad.objects.order_by('?').first()
            if ad:
                # serialize the ad using the AdSerializer
                serializer = AdSerializer(ad)
                # add the ad to the response
                response.append(serializer.data)

    # serialize the response using the PostSerializer
    serializer = self.get_serializer(response, many=True)
    return Response(serializer.data)

Thanks in advance, I hope this explains a lot.

Back to Top