我正在尝试制作一个帖子列表,其中每五个帖子都是广告帖子,所以我想制作一个列表,其中第五个元素都来自广告列表。
我从这个答案中尝试了一些东西https://stackoverflow.com/a/34692876/14790632
将这些对象列表分配到一个列表中,我做错了什么
views.py:
def home(request, pk):
#i tried this
#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)
#and i have tried this below
post_list = Post.objects.all()
ad_list = Ads.objects.all()
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)
models.py:
class Ads(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE, null=True)
编辑:从答案中实现后,我现在得到的是帖子,但不是广告帖子。我想这是因为我正在使用Ads.objects.all((,但我应该把它改成什么?
你正朝着正确的方向前进,试试这个:
def home(request, pk):
post_list = Post.objects.all()
ad_list = Ads.objects.all()
offset = 4
iter1 = iter(post_list)
post_start = 0
post_ad_list = []
for x in ad_list:
post_ad_list.extend(post_list[post_start:post_start + offset])
post_ad_list.append(x)
post_start += offset
context = {
'posts': post_ad_list,
}
return render(request, 'new.html', context)
请注意,循环后无需再次添加帖子
您可以执行此
def home(request, pk):
#i tried this
#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)
#and i have tried this below
post_list = Post.objects.all()
ad_list = Ads.objects.all()
n = 5
iter1 = iter(post_list)
post_ad_list = []
for x in ad_list:
# you select one
# this output only element 5
post_ad_list.extend(post_list[4:5])
post_ad_list.append(x)
# or this if you using this => every 5 data will be retrieved => output: [5,10,15,20]
for i in len(post_list):
if not i % n:
post_ad_list.extend(post_list[i-1:i])
post_ad_list.append(x)
context = {
'posts': post_ad_list,
}
return render(request, 'new.html', context)