【问题标题】:Django unit test "matching query does not exist"Django单元测试“匹配查询不存在”
【发布时间】:2021-02-08 04:05:21
【问题描述】:

我正在尝试对模型进行单元测试,但我不断收到“捐赠匹配查询不存在”,并且回溯指向 test_charity 函数中的第一行。我尝试使用 charity='aclu' 而不是 ID 获取对象,但这并没有解决问题。

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')

我的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)

【问题讨论】:

    标签: python django django-models django-testing django-tests


    【解决方案1】:

    您使用setUp 设置数据。此外,您应该保存主键并使用它,因为数据库可以使用任何主键。根据数据库后端和测试用例的顺序,它可以创建具有不同主键的对象:

    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')

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-28
      • 2022-01-05
      • 2020-10-15
      相关资源
      最近更新 更多