def test_create_post(self): # Create the post post = Post() category = Category(id=1) # Set the attributes post.title = 'My first post' post.text = 'This is my first blog post' post.pub_date = timezone.now() category.title = 'My category' post.category = category # Save it post.save() # Check we can find it all_posts = Post.objects.all() self.assertEquals(len(all_posts), 1) only_post = all_posts[0] self.assertEquals(only_post, post) # Check attributes self.assertEquals(only_post.title, 'My first post') self.assertEquals(only_post.text, 'This is my first blog post') self.assertEquals(only_post.pub_date.day, post.pub_date.day)
category.post_set.all() # [Post] tag.post_set.all() # [Post] # Начало другого урока from blog.models import Category, Post # Создание c = Category(title='Perl') c.save() # За один вызов c = Category.objects.create(title='Python') # create - создать экземпляр модели # Изменение c.title = 'About Python' c.save() # Создание объектов со связями t = Tag(title='easy') t.save() c = Category(title='Python') c.save() p = Post(title='...', ... , category=c или category_id=3) p.save() # Многие ко многим p.tags = Tag.objects.all()[0:3] # [ Tag ] p.save() p.tags.add(t)