如何测试django中具有外键的模型?

时间:2017-06-17 12:31:23

标签: python django python-3.x unit-testing django-tests

我正在使用python 3.5和Django 1.10并尝试在tests.py中测试我的应用程序,但是出现了一个错误,它说:ValueError: Cannot assign "1": "NewsLetter.UserID" must be a "User" instance.那么如何在这里测试fk值? 这是代码:

class NewsletterModelTest(TestCase):

    @classmethod
    def setUpTestData(cls):
        #Set up non-modified objects used by all test methods
        NewsLetter.objects.create(NewsLetterID=1, Email='test@test.com', Connected=False,UserID=1)


    class NewsLetter(models.Model):
         NewsLetterID = models.AutoField(primary_key=True)
         Email = models.CharField(max_length=255)
         Connected = models.BooleanField(default=False)
         UserID = models.ForeignKey(User, on_delete=models.CASCADE)
         class Meta:
              db_table = 'NewsLetter'

3 个答案:

答案 0 :(得分:6)

在setupTestData方法中,您必须创建一个User对象,并将其传递给NewsLetter对象的create方法。

@classmethod
def setUpTestData(cls):
    #Set up non-modified objects used by all test methods
    user = User.objects.create(<fill params here>)
    NewsLetter.objects.create(NewsLetterID=1, Email='test@test.com', Connected=False,UserID=user)

答案 1 :(得分:1)

对于那些登陆这里的人。

要为具有ForeignKey字段的模型编写测试,需要在应用之前创建ForeignKey指向的模型实例,然后在ForeignKey实例上调用save()它可以创建测试的目标模型。

例如(为简便起见,已简化)

class BookTestCase(TestCase):
    def test_fields_author_name(self):
        author = Author(name="Mazuki Sekida")
        author.save()
        book = Book(name="Zen Training", author=author)
        book.save()

        # assertion example ...
        record = Book.objects.get(id=1)
        self.assertEqual(record.author.name, "Mazuki Sekida")         

答案 2 :(得分:0)

与@Arpit Solanki 的回答非常相似,这就是我所做的:

from datetime import date

from django.test import TestCase

from ..models import Post, Author


class PostModelTest(TestCase):
    @classmethod
    def setUpTestData(cls):
        cls.author_ = 'Rambo'
        cls.author = Author.objects.create(name=cls.author_)
        cls.post = Post.objects.create(
            title='A test', author=cls.author, content='This is a test.', date=date(2021, 6, 16))

    def test_if_post_has_required_author(self):
        self.assertEqual(self.post.author.name, self.author_)