Domanda

I've got two model objects inside of a query set

x = [<model.object>]
y = [<model.object>]

I need to process each object through a script for each of the sets

for i in [x,y]:
    i.attribute_1
    i.attribute_2

This wont work though because in this example 'i' is going to represent a query set not an object

for i in [x,y]:
    i[0].attribute_1
    i[0].attribute_2

Seems cumbersome

for i in [x[0],y[0]]:
    i.attribute_1
    i.attribute_2

Same problem

for i[0] in [x,y]:
    i.attribute_1
    i.attribute_2

Doesnt work.

Is there a better soloution than

for i in [x,y]:
    i = i[0]
    i.attribute_1
    i.attribute_2

? Or better yet

z = 0
for i in [x,y]:
    i = i[z]
    i.attribute_1
    i.attribute_2
    z += 1

? Thanks :)

È stato utile?

Soluzione 2

I think i have it

for i in [x,y]:
    z = 0
        while z < len(i)
        o = i[z]
        o.attribute_1
        o.attribute_2
        z += 1

Altri suggerimenti

What you probably want to do here is:

for index, pair in enumerate(zip(x, y)):
   current_x, current_y = pair
   # do stuff with index, current_x, current_y ...

Looks like itertools.chain applies best for this case:

for i in itertools.chain(x, y):
    i.attr_1
    i.attr_2

It can also be applied to situation, where you have a list of query sets, like that:

query_sets = [[<model.object>, <model.object>], [<model.object>, <model.object>, <model.object>], ....]
for i in itertools.chain(*query_sets):
    ....
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top