开发者

Django Query in a loop fails for no good reason

开发者 https://www.devze.com 2022-12-21 17:40 出处:网络
I have this code: msgs = int(post[\'time_in_weeks\']) for i in range(msgs): tip_msg = Tip.objects.get(week_number=i)

I have this code:

msgs = int(post['time_in_weeks'])
for i in range(msgs):
    tip_msg = Tip.objects.get(week_number=i)

it always results in an error saying that no values could be found.

week_number is an integer field. When I input the value of i directly, th开发者_运维知识库e query works.

When i print out the value of i I get the expected values.

Any input at all would be seriously appreciated.

Thanks.


The range function will give you a zero based list of numbers up to and excluding msgs. I guess there is no Tip with week_number=0.


Also, to limit the number of queries you could do this:

for tip in Tip.objects.filter(week_number__lt=msgs):
    #do something

or, if you want specific weeks:

weeks=(1,3,5)
for tip in Tip.objects.filter(week_number__in=weeks):
    #do something
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号