【问题标题】:Django entry creating. Method in views/other file or as a method of model classDjango 条目创建。视图/其他文件中的方法或作为模型类的方法
【发布时间】: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)

我之所以问,是因为我已经看到了将内容添加到数据库的两种方法。我想问一下:

  1. 什么是更好的做法?
  2. 对第二个示例中的安全性有任何担忧吗?

【问题讨论】:

  • 安全问题是什么意思?在我看来,第一种方式更干净,因为您阅读它的时间就知道记录已保存。不过我看不出有什么大的区别(除了你的最后一个 sn-p 中不存在 abc 和 xyz 变量:P)。

标签: django views models


【解决方案1】:

在我看来,选项 1 是更好的做法。 add_article 是不必要的,因为您可以使用日期字段的auto_now 属性设置日期,其他所有内容都已内置。您将拥有更少的代码和更少的维护。

【讨论】:

  • 我也会选择选项 1。将 add_article 之类的方法添加到模型本身感觉不对。至少因为它是一个不直观的 API。在文章中添加文章?听起来不对,是吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-07-17
  • 1970-01-01
  • 2023-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多