Home > Mobile >  'QuerySet' object has no attribute 'pk' in "bulk_update"
'QuerySet' object has no attribute 'pk' in "bulk_update"

Time:03-26

I have model of Professor and need to "bulk_update". I have to do this in 2 requests from my DB. But i have exception ('QuerySet' object has no attribute 'pk'). If i use get i have another exception(get() returned more than one Professor).

My model.

 class Professor(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    age = models.IntegerField(default=18)
    class Meta:
        indexes = [models.Index(fields=['first_name'])]

My code

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

Can you give me some advices about it?

CodePudding user response:

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'])
  • Related