Reputation: 1313
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
Upvotes: 2
Views: 1275
Reputation: 35002
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]
Upvotes: 2