Search code examples
djangodjango-modelsdjango-testing

Testing model - how to create records


according to https://docs.djangoproject.com/en/1.9/topics/testing/overview/ :

from django.test import TestCase
from myapp.models import Animal

class AnimalTestCase(TestCase):
    def setUp(self):
        Animal.objects.create(name="lion", sound="roar")
        Animal.objects.create(name="cat", sound="meow")

    def test_animals_can_speak(self):
        """Animals that can speak are correctly identified"""
        lion = Animal.objects.get(name="lion")
        cat = Animal.objects.get(name="cat")
        self.assertEqual(lion.speak(), 'The lion says "roar"')
        self.assertEqual(cat.speak(), 'The cat says "meow"')

I want to create setUp to my model class:

class Post(models.Model):
    author = models.ForeignKey('auth.User')
    tags = models.ManyToManyField('blogUserPlane.Tag')
    title = models.CharField(max_length=200)
    text = models.TextField()
    created_date = models.DateTimeField(
        default=timezone.now)
published_date = models.DateTimeField(
    blank=True, null=True)

This is my NOT WORKING setUp:

def setUp(self):
    Post.objects.all().create(author=User(), tag=models.ManyToManyField('blogUserPlane.Tag'), title="title1", text="text1", created_date=None, published_date=None)

What is correct way to create records of model with ManyToManyField and ForeginKey?


Solution

  • If you want to enter a value in a ForeignKey or ManyToMany field ,you first need to import that value . For example if you want to enter a value in author field ,

    from django.contrib.auth.models import User
    user = User.objects.get(username = 'your_username')
    Post.objects.create(author = user)