Zach R
Zach R

Reputation: 131

Django ForeignKey on_delete = SET_NULL not working

I'm writing tests for several object models and the following test isn't giving the expected result:

def test_image_on_delete(self):
    image = Image(id=self.TEST_IMAGE_ID, name=self.TEST_IMAGE_NAME, src=self.TEST_IMAGE_SRC)
    image.save()
    category = Category.objects.get(id=self.TEST_ID)
    category.image = Image.objects.get(id=self.TEST_IMAGE_ID)
    Image.objects.get(id=self.TEST_IMAGE_ID).delete()
    self.assertIsNone(category.image)

Here is the image field in Category:

image = ForeignKey(Image, on_delete=SET_NULL, null=True)

I've confirmed that the Image is being deleted, but the assertIsNone fails because the Category's image field doesn't get cleared.

Is there something wrong with the way I've written this test or the ForeignKey field?

Note: I'm using TestCase from django.test

Upvotes: 1

Views: 550

Answers (2)

Serrano
Serrano

Reputation: 1517

You can refresh your object from the database:

category.image.delete()

# Reload the object from the database.
category.refresh_from_db()

self.assertIsNone(category.image)

Documentation:

https://docs.djangoproject.com/en/3.2/ref/models/instances/#refreshing-objects-from-database

Upvotes: 1

Zach R
Zach R

Reputation: 131

I figured out the issue. on_delete modifies the SAVED version of my Category object, so the copy of the variable I have locally isn't changed.

Here's my modified test that passes:

def test_image_on_delete(self):
    image = Image(id=self.TEST_IMAGE_ID, name=self.TEST_IMAGE_NAME, src=self.TEST_IMAGE_SRC)
    image.save()
    category = Category.objects.get(id=self.TEST_ID)
    category.image = Image.objects.get(id=self.TEST_IMAGE_ID)
    self.assertIsNotNone(category.image)
    category.save()
    Image.objects.get(id=self.TEST_IMAGE_ID).delete()
    category = Category.objects.get(id=self.TEST_ID)
    self.assertIsNone(category.image)

Upvotes: 0

Related Questions