2

I would like to do something like this:

before = [ rec.field for rec in all_relevant_records ]

# Do some operation on the all_relevant_records:
for rec in all_relevant_records:
    rec_pk = rec.pk
    new_field = get_new_field(rec, field)
    db.objects.filter(pk=rec_pk).update(field=new_field)

after = [ rec.field for rec in all_relevant_records ]

But, this does not work as field cannot be resolved into a queryset field.

I have looked at How to dynamically provide lookup field name in Django query? But, this is not quite what I want.

Any help appreciated

Community
  • 1
  • 1
EarlyCoder
  • 1,213
  • 2
  • 18
  • 42

1 Answers1

2

When you do:

db.objects.filter(pk=rec_pk).update(field=new_field)

you are using keyword arguments. Which is equivalent to:

db.objects.filter(**{'pk': rec_pk}).update(**{'field': new_field})

so if field is not the name of your field, but a variable containing the name of your field, what you want to do is:

db.objects.filter(pk=rec_pk).update(**{field: new_field})

About this:

before = [ rec.field for rec in all_relevant_records ]

I'm not sure what you are trying to achieve, but I guess it should be something like this:

before = [getattr(rec, field) for rec in all_relevant_records]
Antoine Pinsard
  • 33,148
  • 8
  • 67
  • 87
  • Very well explained! Your answer does address one of the two problems I had. The second problem was how to dynamically get the field in before and after list comprehensions. Do you happen to have an idea? – EarlyCoder Mar 13 '16 at 17:32
  • I don't understand what you are trying to do. Could you please explain it with words? What are `before` and `after` supposed to be? I edited my answer but I'm not sure that's what you are trying to achieve. – Antoine Pinsard Mar 13 '16 at 17:39
  • Thank you Antoine! It was a lot of timely help – EarlyCoder Mar 13 '16 at 18:43