[Django]-'QuerySet' object has no attribute 'pk' in "bulk_update"

2๐Ÿ‘

โœ…

Your prof is a QuerySet of Professors, not a single Professor, hence it is non sensical to write prof.first_name = new_first_name, and it will also result in tmp being a list of the same QuerySet repeated multiple times.

You should look up the Professor object, and assign it accordingly, so:

def update_professor_first_names(first_name_updates: List[NameUpdate]):
    prof_id = [id for id, name in first_name_updates]
    profs = {p.id: p for p in Professor.objects.filter(id__in=prof_id)}
    tmp = []
    for prof_id, new_first_name in first_name_updates:
        prof = profs[prof_id]
        prof.first_name = new_first_name
        tmp.append(prof)
    Professor.objects.bulk_update(tmp, ['first_name'])

0๐Ÿ‘

Add .first() or [:1] to the end of your query like so:

prof = Professor.objects.filter(id__in=prof_id).first()
or

prof = Professor.objects.filter(id__in=prof_id)[:1]

This way, you can do prof.first_name = new_first_name

๐Ÿ‘คalkadelik

Leave a comment