Home > Net >  Foreign Key TestCase
Foreign Key TestCase

Time:10-30

I am trying to run tests on models and am having trouble with ones that have a foreign key. When I try to get the card made in setUp I am not able to. I am not understanding why. The value expected for the attribute category is an int. Either category, category.id, nor 'Test Category' work.

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

Error:

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.

CodePudding user response:

Instead of providing the category.id just give the category object itself.

card = Card.objects.filter(category=category,
                                question='Hello?',
                                answer='Hello!',
                                slug='slug'
                                )

I am using filter instead of get in case you have multiple object for the given parameters.

  • Related