Search code examples
pythondjangodjango-modelsdjango-testingdjango-tests

Django unit test "matching query does not exist"


I'm trying to unit test a model but I keep getting "Donation matching query does not exist," with the traceback pointing to the first line in the test_charity function. I tried getting the object with charity='aclu' instead of by ID, but that did not fix it.

from django.test import TestCase
from .models import Donation


class DonateModelTest(TestCase):

    def init_data(self):
        #print("got here")
        x = Donation.objects.create(charity='aclu', money_given=15)
        # print(x.id)

    def test_charity(self):
        donation = Donation.objects.get(id=1)
        field_label = donation._meta.get_field('charity').verbose_name
        self.assertEquals(field_label, 'charity')

My models.py:

from django.db import models

class Donation(models.Model):
    DONATE_CHOICES = [
        ('aclu', 'American Civil Liberties Union'),
        ('blm', 'Black Lives Matter'),
        ('msf', 'Medecins Sans Frontieres (Doctors Without Borders)')
    ]

    charity = models.CharField(
        max_length=4,
        choices=DONATE_CHOICES,
        default='aclu'
    )

    money_given = models.IntegerField(default=0)

Solution

  • You setUp data with setUp. Furthermore you should save the primary key, and use this since a database can use any primary key. Depending on the database backend, and the order of the test cases, it thus can create an object with a different primary key:

    class DonateModelTest(TestCase):
    
        def setUp(self):
            self.pk = Donation.objects.create(charity='aclu', money_given=15).pk
    
        def test_charity(self):
            donation = Donation.objects.get(id=self.pk)
            field_label = donation._meta.get_field('charity').verbose_name
            self.assertEquals(field_label, 'charity')