I have a recipients query containing two recipients with the ID 1 and 2: I loop over each one to build json output:
    data = []
    this_tem = {}
    for item in recipients:
        this_tem['recipient_id'] = item.pk
        data.append(this_tem)
    return HttpResponse(json.dumps(data), mimetype='application/json')
This gives me:
[
    {
        "recipient_id": 2,
    },
    {
        "recipient_id": 2,
    }
]
As you can see it should be recipient_id 1 and recipient_id 2 however, my loop overwrites the value, why?
this_tem is a reference to a single object (a dict) which you repeatedly modify and append in your loop. You overwrite the value of that key in the loop.
You need to create a new dict each iteration:
data = []
for item in recipients:
    this_tem = {}
    this_tem['recipient_id'] = item.pk
    data.append(this_tem)
Edit
As Grijesh Chauhan graciously pointed out, the expression and loop can be simplified vis a vie a list comprehension:
data = [{'recipient_id': item.pk} for item in recipients]
                        You're appending a dictionary, which is a mutable object.
So after your loop, data contains two references to the same dictionary.
You'll have to append new dictionaries in each iteration, e.g. like this:
for item in recipients:
    data.append(dict(recipient_id = item.pk))
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With