如何在Django中将每个第五个帖子发布为一个广告帖子 [英] How To Make Every Fifth Post An Ad Post In Django
问题描述
我正试图允许用户赞助一个帖子,以使更多的点击进入该帖子.我想将每五分之一的帖子设为赞助帖子,但是如果我尝试在模板中使用被整除并遍历广告,那么它将在第四篇帖子之后发布 all 所有广告
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
我已将问题更改为不显示帖子的内容,有人可以告诉我我错了吗?
I have changed the question to something that won't show the posts can someone show me where i'm wrong?
型号:
class Ads(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE, null=True)
观看次数:
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 %}
推荐答案
好,因此您可以枚举 Post
查询集,以便可以每x个对象插入一个广告.这将成为一种冗长且易于理解的方法.
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.
或者您可以使用 itertools
中的 chain
做一些事情;
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']
如您所见,每5个元素就会添加一个广告".
So as you can see there, an 'Ad' is added every 5 elements.
如果将两个查询集转换为列表,则可以执行 ads.pop()
将元素插入到帖子列表中.
If you convert you two querysets into lists, you could do ads.pop()
to insert the element into the list of posts.
这篇关于如何在Django中将每个第五个帖子发布为一个广告帖子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!