Почему я получаю "Ошибку ключа" в этом коде Django Rest Framework?

Я пытаюсь показать рекламу после каждого 10-го сообщения в моей ленте в Django rest framework с отдельной моделью объявления и сообщения. Я действительно застрял и буду очень признателен всем, кто поможет мне решить эту проблему. Вот мой код:

Моя почта и рекламная модель

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']

Мои взгляды

 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)

Заранее спасибо, надеюсь, это многое объясняет.

Вернуться на верх