我正在嘗試對模型進行測驗,但在使用具有外鍵的模型時遇到了問題。當我嘗試制作卡片時,setUp我無法做到。我不明白為什么。該屬性的預期值category是一個 int。category, category.id, 或 'Test Category' 都可以。
代碼:
models.py
class Category(models.Model):
category_name = models.CharField(max_length=32)
class Card(models.Model):
category = models.ForeignKey(Category, on_delete=models.CASCADE)
question = models.CharField(max_length=255)
answer = models.TextField()
slug = models.SlugField()
test_models.py
class CardTestCase(TestCase):
def setUp(self) -> None:
category = Category.objects.create(category_name='Test Category')
Card.objects.create(category=category,
question='Hello?',
answer='Hello!',
slug='slug'
)
def test_card_exists(self):
category = Category.objects.get(category_name='Test Category')
L29 card = Card.objects.get(category=category.id,
question='Hello?',
answer='Hello!',
slug='slug'
)
錯誤:
line 29, in test_card_exists
card = Card.objects.get(category=category.id,
django_cards.cards.models.Card.DoesNotExist: Card matching query does not exist.
uj5u.com熱心網友回復:
而不是category.id只提供類別物件本身。
card = Card.objects.filter(category=category,
question='Hello?',
answer='Hello!',
slug='slug'
)
如果給定引數有多個物件,我將使用過濾器而不是獲取。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/523252.html
上一篇:嘗試從他的子類訪問父變數時出錯
下一篇:從“CustomerService”測驗“createCustomer”方法時出現NullPointerException
