如何在不使用数组的方法中返回循环值,现在我正在使用数组。
这是我的代码:
def get_ticket_sum_quantity(self, product_id, date_select):
prod = Product.objects.get(id=product_id)
sumOfQuantity = Ticket.objects.filter(date_select=date_select, product=prod).aggregate(Sum('quantity'))['quantity__sum']
if sumOfQuantity == None:
sumOfQuantity = 0
prodAvailable = prod.quantity - sumOfQuantity
return prodAvailable
def get_ticket_available_product(self, date_select, client_id, quantity):
client = Client.objects.get(id=client_id)
prodCount = Product.objects.filter(client=client_id,status='Active').values_list('id', flat=True)
array = []
for id in prodCount:
prodAvailable = Ticket.objects.get_ticket_sum_quantity(id, date_select)
prodAvailable = prodAvailable - quantity
if prodAvailable < 0:
data = {'id':id}
else :
data = {'id':id}
data = data['id']
array.append(data)
return array
当我使用它时,输出是......
Ticket.objects.get_ticket_available_product('2011-12-29', 5, 1)
[3, 2, 6, 1]
我的问题是,是否有其他选项我不会使用数组,以便它会像这样返回?
3
2
6
1
答案 0 :(得分:2)
是的,您可以使用
将您的函数转换为生成器,以便在每次调用后返回下一个值,或者如果没有要返回的值,则生成StopIteration。
def get_ticket_available_product(self, date_select, client_id, quantity):
client = Client.objects.get(id=client_id)
prodCount = Product.objects.filter(client=client_id,status='Active').values_list('id', flat=True)
for id in prodCount:
prodAvailable = Ticket.objects.get_ticket_sum_quantity(id, date_select)
prodAvailable = prodAvailable - quantity
if prodAvailable < 0:
data = {'id':id}
else :
data = {'id':id}
data = data['id']
yield data
return
用法
data = get_ticket_available_product(self, date_select, client_id, quantity)
for d in data:
print d
实施例
print '\n'.join(str(i) for i in [3, 2, 6, 1])
或在本案例中
print '\n'.join(str(i) for i in Ticket.objects.get_ticket_available_product('2011-12-29', 5, 1) )
或者您可以以这种方式拆分返回值。请记住,在这种情况下,返回值将是一个字符串
data = data['id']
array.append(data)
return '\n'.join(str(i) for i in array )
用法:
print Ticket.objects.get_ticket_available_product('2011-12-29', 5, 1)
顺便说一下:
此代码段的用途是什么?
if prodAvailable < 0:
data = {'id':id}