how to test a model that has a foreign key in django?

mg22 picture mg22 · Jun 17, 2017 · Viewed 8.1k times · Source

I'm using python 3.5 and Django 1.10 and trying to test my app in tests.py, but an error appeared, it said: ValueError: Cannot assign "1": "NewsLetter.UserID" must be a "User" instance. so how to test a fk value here? here is the code:

class NewsletterModelTest(TestCase):

    @classmethod
    def setUpTestData(cls):
        #Set up non-modified objects used by all test methods
        NewsLetter.objects.create(NewsLetterID=1, Email='[email protected]', 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'

Answer

Arpit Solanki picture Arpit Solanki · Jun 17, 2017

In your setupTestData method you have to create a User object, and pass it into the NewsLetter object create method.

@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='[email protected]', Connected=False,UserID=user)