S
S
Sergey Lazarevic2021-10-18 10:05:44
Django
Sergey Lazarevic, 2021-10-18 10:05:44

How to make an object of another model iterate after 2 iterations of the first, etc.?

How to make it so that, say, every two posts (Post - a separate model) only one banner appears (Banner - a separate model) and then again two posts and a banner, and so on.
Here is an example output diagram:

post1, post2
banner1
post3, post4
banner4

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim, 2021-10-18
@Tomio

For example, like this:

banners = ['banner1', 'banner2', 'banner3']
posts = ['post1', 'post2', 'post3', 'post4', 'post5', 'post6', 'post7', 'post8']
banner_step = 2
for index, post in enumerate(posts):
    print(post)
    if (index+1) % banner_step == 0 and banners:
        print(banners.pop(0))

The output will be like this:
post1
post2
banner1
post3
post4
banner2
post5
post6
banner3
post7
post8

Just keep in mind that after each banners.pop(0) command, the list of banners will decrease. If you need to save the original list, then you will need to make a copy of this list and already do .pop (0) in it

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question