Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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'
like image 266
mg22 Avatar asked Jun 17 '17 12:06

mg22


People also ask

How do foreign keys work in Django?

Introduction to Django Foreign Key. A foreign key is a process through which the fields of one table can be used in another table flexibly. So, two different tables can be easily linked by means of the foreign key. This linking of the two tables can be easily achieved by means of foreign key processes.

How do I test a Django project?

The preferred way to write tests in Django is using the unittest module built-in to the Python standard library. This is covered in detail in the Writing and running tests document. You can also use any other Python test framework; Django provides an API and tools for that kind of integration.

How do I add a ForeignKey to a Django model?

Create a (default) object of the foreign model. It will automatically have id=1 (if no object existed yet). Change your foreignkey field by replacing null=True, blank=True by default=1 to associate that new object you created to all existing rows.

Can a model have two foreign keys Django?

Your intermediate model must contain one - and only one - foreign key to the source model (this would be Group in our example). If you have more than one foreign key, a validation error will be raised.


1 Answers

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)
like image 110
Arpit Solanki Avatar answered Sep 28 '22 17:09

Arpit Solanki