[Django]-Unit Testing Django Model Save Function

4👍

If you find yourself here, you’d be better off reloading the object with Model.refresh_from_db(using=None, fields=None). See the Django documentation

Also checkout Reload django object from database

6👍

Solved!

Custom save functions correctly update the database, but not the model instance being tested! Need to refresh the model instance to get any updates by calling it again with something like [model].objects.get()

e.g.:

    asset = Asset.objects.create(asset_description="Test Asset 2", requires_calibration=True)
    self.assertIsNone(asset.calibration_date_prev)
    CalibrationRecord.objects.create(asset=asset, calibration_description="Test Calibration 2",
                                     calibration_date=timezone.now())
    cal = CalibrationRecord.objects.get(calibration_description="Test Calibration 2")
    asset = Asset.objects.get(asset_description="Test Asset 2")
    self.assertEqual(cal.calibration_date, asset.calibration_date_prev)
👤TimJ

Leave a comment