如何在 Django 中让每五个帖子成为一个广告帖子 [英] How To Make Every Fifth Post An Ad Post In Django
问题描述
我试图让用户赞助一个帖子,以便为该帖子带来更多点击.我想每五个帖子发布一个赞助帖子,但如果我尝试在模板中使用可除数并循环浏览广告,那么它将在第四个帖子后发布所有广告
这是我试过的一些代码
我已将问题更改为不显示帖子的内容,有人可以告诉我我错在哪里吗?
型号:
类广告(models.Model):post = models.ForeignKey(发布,on_delete=models.CASCADE,null=True)
观看次数:
def home(request, pk):post_list = []广告列表 = []对于 Post.objects.all() 中的 p:post_list.append(p.Post)对于 Ads.objects.all() 中的 a:ad_list.append(p.Ads)n = 5iter1 = iter(post_list)post_ad_list = []对于 ad_list 中的 x:post_ad_list.extend([next(iter1) for _ in range(n - 1)])post_ad_list.append(x)post_ad_list.extend(iter1)上下文 = {帖子":post_ad_list,}返回渲染(请求,'new.html',上下文)
我尝试过但不起作用的模板:
{% 用于帖子中的项目 %}//打印产品和广告{% 结束为 %}
好的,这样你就可以枚举你的 Post
查询集,这样你就可以每 x 个对象插入一个广告.这将形成一种冗长且易于理解的方法.
或者你可以用 itertools
中的 chain
做一些类似这样的事情;
如您所见,每 5 个元素添加一个广告".
如果将两个查询集转换为列表,则可以执行 ads.pop()
将元素插入到帖子列表中.
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 %}
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.
这篇关于如何在 Django 中让每五个帖子成为一个广告帖子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!