0

I have a method on a model that updates a value to 0.0 and calls save(). Problem is save() is never saving the value if it is 0.

Here is the code:

class Item(models.Model):
    stock_quantity = models.FloatField(
        null=True, blank=True, validators=[MinValueValidator(0)]
    )

    class Meta:
        abstract = True
        ordering = ["-id"]

    def mark_as_finished(self) -> None:
        self.stock_quantity = 0.0
        self.save()

I have a submodel which extends this one.

class Instance(Item):
    expiration_date = models.DateField(null=True, blank=True)

Now the mark_as_finished() is called in the view:

@action(detail=True, methods=["patch"], url_name="mark-as-finished")
def mark_as_finished(self, request: Request, pk: int) -> Response:
    pi_instance = get_object_or_404(Instance, id=pk)
    pi_instance.mark_as_finished()
    pi_instance.refresh_from_db()
    return Response(
        data=self.serializer_class(pi_instance).data,
        status=HTTP_200_OK,
    )

Upon running the test the stock value never becomes 0.

def test_mark_as_finished(self):
    pink_ins = self.create_sample_instance()
    self.assertNotEqual(pink_ins.stock_quantity, 0)
    url: str = reverse(self.mark_finished_url, kwargs={"pk": pink_ins.id})
    res: HttpResponse = self.client.patch(url)
    self.assertEqual(res.status_code, 200)
    self.assertEqual(res.data["stock_quantity"], 0)

self.assertEqual(res.data["stock_quantity"], 0) AssertionError: 10.5 != 0

I am debugging the program and can see that after the save runs the value is never being saved. If I put the value as 0.1 then it saves. So actually it is not saving 0 value in the float field. I even removed the MinimumValueValidator still it won't save 0 value.

Sardar Faisal
  • 594
  • 5
  • 20

0 Answers0