Django Model reference assignment in loop
<p>Is the following code correct? The <code>e</code> should refer to  a new object in the beginning of each for iteration, after try/except blocks are executed. I suspect some interference with an old object, because there is a bug which I cannot reproduce now.</p>

<pre><code> 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
</code></pre>

<p>If you want all the try/catch blocks to run within the for loop you need make sure your identation is correct</p>

<p>Try (check the indentation)</p>

<pre><code>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
</code></pre>

python django