Django 创建条目。
1)如 Django 文档中所见:
class Article(models.Model):
user = models.ForeignField(User)
title = models.CharField(#some_params)
content = models.CharField(#some_params)
date = models.DateTimeField(#some_params)
那么在我看来,我可以:
new_article = Article(user=user, title="abc", content="xyz", date = datetime.utcnow())
new_article.save()
2)但也可以通过在 Article 类中调用方法来完成,即:
class Article(models.Model):
user = models.ForeignField(User)
title = models.CharField()
content = models.CharField()
def add_article(self, title, content):
self.title = title
self.content = content
self.date = datetime.utcnow()
self.save()
然后在视图中:
title = "abc"
content = "xyz"
new_article = Article(user=user)
new_article.add_article(abc, xyz)
我问是因为我已经看到了将内容添加到数据库中的两种方法。我想问一下:
- 什么是更好的做法?
- 对第二个示例中的安全性有任何担忧吗?