Adam Starrh
Adam Starrh

Reputation: 6958

Django .save() unpredictably processing update_fields input

The traceback tells the story:

Error
Traceback (most recent call last):
  File "/Users/adamstarrh/almondking/AlmondKing/tests/test_models/test_financial_logs.py", line 35, in test_cogs_per_tag
    self.assertEqual(self.sale5.cogs_per_tag, {10: 1813365, 3: 5623801, 4: 4140737})
  File "/Users/adamstarrh/almondking/AlmondKing/FinancialLogs/models.py", line 244, in cogs_per_tag
    cogs[tag[0]] = float(round(shipment.adjusted_cost * tag[1]))
  File "/Users/adamstarrh/almondking/AlmondKing/InventoryLogs/models.py", line 509, in adjusted_cost
    return self.cost_inr_per_kg
  File "/Users/adamstarrh/almondking/AlmondKing/InventoryLogs/models.py", line 499, in cost_inr_per_kg
    Decimal(self.reverse_exchange_rate), 4)
  File "/Users/adamstarrh/almondking/AlmondKing/InventoryLogs/models.py", line 477, in reverse_exchange_rate
    self.save(update_fields="rate_usd_inr")
  File "/Users/adamstarrh/almondking/AlmondKing/lib/python3.5/site-packages/django/db/models/base.py", line 714, in save
    % ', '.join(non_model_fields))
ValueError: The following fields do not exist in this model or are m2m fields: u, _, n, a, r, s, e, t, i, d

When I try to call self.save(update_fields="rate_usd_inr"), instead of updating the field provided in the string, it looks for fields with each individual character in the string.

This has been working fine for me for months. I am pretty sure I ran my tests successfully when I stopped working yesterday. I certainly never ran into it while I was working on my code. It just started showing up when I ran them again this morning.

Upvotes: 4

Views: 1136

Answers (1)

alecxe
alecxe

Reputation: 473873

update_fields should be an iterable with the field names inside:

The update_fields argument can be any iterable containing strings. An empty update_fields iterable will skip the save. A value of None will perform an update on all fields.

self.save(update_fields=["rate_usd_inr"])

Upvotes: 5

Related Questions