我试图用Django做一些练习并编写一个简单的博客应用程序。我想使用脚本创建我的模型,所以我不必使用shell或管理界面。
给出以下代码:
def populate():
current_user = User.objects.get(username='testuser')
blogger_data = {'user': current_user,'bio':"this is my test bio", 'likes': 5,}
blogger = add_blogger(blogger_data)
print("Registered blogger : %s" %blogger.user)
for num in range(5):
post_data = {'author':current_user, 'title':"test title %s"%num, 'description': "test description%s"%num, 'content': "test content%s"%num,}
posted_date = datetime.datetime.today() + datetime.timedelta(days=1)
post = add_post(post_data,num,posted_date)
comment_data = {'author':current_user, 'post':post,'content':"test content %s"%num, 'upvotes':num, 'downvotes':5-num,}
comment = add_comment(comment_data)
response_data = {'author':current_user, 'comment':comment, 'content':"test response %s"%num, 'upvotes':5-num, 'downvotes':num,}
response = add_response(response_data)
print("Saved post : %s, comment: %s, response: %s..." %(post,comment,response))
print("Script succesfully saved data!")
def add_post(data_dict,views, posted_date):
post = Post.objects.get_or_create(author=data_dict['author'])[0]
post.title = data_dict['title']
post.description = data_dict['description']
post.content = data_dict['content']
post.views = views
post.posted_date = posted_date
post.save()
return post
def add_comment(data_dict):
c = Comment.objects.get_or_create(author=data_dict['author'],post=data_dict['post'])[0]
c.content = data_dict['content']
c.upvotes = data_dict['upvotes']
c.downvotes = data_dict['downvotes']
c.save()
return c
def add_response(data_dict):
r = Response.objects.get_or_create(author=data_dict['author'],comment=data_dict['comment'])[0]
r.content = data_dict['content']
r.upvotes = data_dict['upvotes']
r.downvotes = data_dict['downvotes']
r.save()
return r
def add_blogger(data_dict):
blogger = Blogger.objects.get_or_create(user=data_dict['user'])[0]
blogger.bio = data_dict['bio']
blogger.likes = data_dict['likes']
blogger.save()
return blogger
if __name__=='__main__':
print("Starting Blog population script...")
populate()
型号:
class Post(models.Model):
author = models.ForeignKey(User)
title = models.CharField(max_length=64, help_text="The post's title.", unique=True)
description = models.CharField(max_length=128, help_text="A short description of the post.")
content = models.CharField(max_length=8192, help_text="Your post content.")
views = models.IntegerField(default=0)
slug = models.SlugField(blank=True)
created_date = models.DateField(default=timezone.now)
posted_date = models.DateField(blank=True,null=True)
def __str__(self):
return self.title
def save(self, *args, **kwargs):
self.slug = slugify(self.title)
if not self.posted_date:
self.posted_date = datetime.today()
super(Post, self).save(*args, **kwargs)
class Comment(models.Model):
author = models.ForeignKey(User)
post = models.ForeignKey(Post)
content = models.CharField(max_length=1024)
upvotes = models.IntegerField(default=0)
downvotes = models.IntegerField(default=0)
def __str__(self):
return "%s (%s)(%s)"%(self.content[:20]+"...",self.post,self.author)
class Response(models.Model):
author = models.OneToOneField(User,primary_key=True)
comment= models.ForeignKey(Comment, models.SET_NULL, blank=True, null=True)
content = models.CharField(max_length=1024, help_text="Your message in response to a desired comment.")
upvotes = models.IntegerField(default=0)
downvotes = models.IntegerField(default=0)
def __str__(self):
return "%s (%s)(%s)" % (self.content[:20]+"...",self.author,self.content)
class Blogger(models.Model):
user = models.OneToOneField(User, primary_key=True)
bio = models.CharField(max_length=1024, help_text="A short bio that viewers can see about you.")
profilepic = models.ImageField(upload_to='profilepics')
likes = models.IntegerField(default=0)
joined_date = models.DateField(default=datetime.today)
def __str__(self):
return user.username
def save(self, *args, **kwargs):
self.joined_date = timezone.now()
super(Blogger, self).save(*args, **kwargs)
运行脚本后,只有在循环的最后一次迭代中创建的模型实例才会保存在数据库中。 究竟发生了什么?
答案 0 :(得分:0)
您只有一个用户,您可以在每次迭代中使用它。这意味着您对Post的get_or_create
调用将在第一次迭代中为该用户创建帖子,但在每次后续迭代中都将获取现有实例并更新它。随后对其余函数的调用将执行与它们依次传递Post和Comment相同的操作。