[英]Django unit test "matching query does not exist"
我正在嘗試對 model 進行單元測試,但我不斷收到“捐贈匹配查詢不存在”,回溯指向 test_charity function 中的第一行。我嘗試使用charity='aclu'
而不是 ID 來獲取 object ,但這並沒有解決它。
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')
我的模型.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)
您使用setUp
設置數據。 此外,您應該保存主鍵並使用它,因為數據庫可以使用任何主鍵。 根據數據庫后端和測試用例的順序,它可以創建一個具有不同主鍵的 object:
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')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.