循环中的Django模型引用赋值

时间:2016-09-15 15:49:44

标签: python django

以下代码是否正确?在执行try / except块之后,e应该在每个迭代开始时引用一个新对象。我怀疑对旧物体有些干扰,因为有一个我现在无法重现的错误。

 from webapp.models import Profile

....
    for e in Profile.objects.all():
        if not e.profile_link in profile_data:
            e.delete()

    try:
        for key, employee in profile_data.iteritems():
            #e still holds old reference
            try:
                #edit DB object if exists
                e = Profile.objects.all().filter(profile_link=key)[0]
            except Exception:
                #or create a new one
                e = Profile(profile_link=key)

            #modify e using employee

            e.save()
    except Exception:
        #handle exception

1 个答案:

答案 0 :(得分:0)

如果您希望所有try / catch块在for循环中运行,则需要确保您的标识正确

尝试(检查缩进)

from webapp.models import Profile

....
for e in Profile.objects.all():
    if not e.profile_link in profile_data:
        e.delete()
    try:
        for key, employee in profile_data.iteritems():
            #e still holds old reference
            try:
                #edit DB object if exists
                e = Profile.objects.get(profile_link=key)
            except Exception:
                #or create a new one
                e = Profile(profile_link=key)

            #modify e using employee

            e.save()
    except Exception:
        #handle exception
相关问题