【发布时间】:2013-01-02 02:15:04
【问题描述】:
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)
我之所以问,是因为我已经看到了将内容添加到数据库的两种方法。我想问一下:
- 什么是更好的做法?
- 对第二个示例中的安全性有任何担忧吗?
【问题讨论】:
-
安全问题是什么意思?在我看来,第一种方式更干净,因为您阅读它的时间就知道记录已保存。不过我看不出有什么大的区别(除了你的最后一个 sn-p 中不存在 abc 和 xyz 变量:P)。