Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
551 views
in Technique[技术] by (71.8m points)

How To Make Every Fifth Post An Ad Post In Django

I am trying to allow users to sponsor a post to bring more clicks to there posts. I want to make every fifth post a post that is a sponsored post but if i try to just use divisible by in the templates and loop through ads then it will post all of the ads after the fourth post

here is some code i have tried

EDIT:I have changed the question to something that won't show the posts can someone show me where i'm wrong?

models:

class Ads(models.Model):
    post = models.ForeignKey(Post, on_delete=models.CASCADE, null=True)

views:

def home(request, pk):
    
   post_list = []
   ad_list = []
   for p in Post.objects.all():
       post_list.append(p.Post) 
   for a in Ads.objects.all():
       ad_list.append(p.Ads) 
   n = 5
   iter1 = iter(post_list)
   post_ad_list = []
   for x in ad_list:
       post_ad_list.extend([next(iter1) for _ in range(n - 1)])
       post_ad_list.append(x)
   post_ad_list.extend(iter1)

   context = {
       'posts': post_ad_list,
   }
return render(request, 'new.html', context)

templates i have tried but don't work:

{% for item in posts %}

    //prints products and ads

   
{% endfor %}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Ok, so you could enumerate your Post queryset so that you can insert an ad every x objects. This would make for a verbose and easily understandable approach.

Or you could do something with chain from itertools a bit like this;

>>> N = 5  # element to insert ad
>>> k = 'Ad'  # Thing added to the list
>>>
>>> list(chain(*[letters[i : i+N] + [k] if len(letters[i : i+N]) == N else letters[i : i+N] for i in range(0, len(letters), N)]))
['a', 'b', 'c', 'd', 'e', 'Ad', 'f', 'g', 'h', 'i', 'j', 'Ad', 'k', 'l']

So as you can see there, an 'Ad' is added every 5 elements.

If you convert you two querysets into lists, you could do ads.pop() to insert the element into the list of posts.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...