Django中的面向对象。在这种情况下,最佳做法是什么?

时间:2014-06-03 04:22:54

标签: python django object orientation

案例如下: 用户可以评论文章。所以我有一个评论模型,一个文章模型和一个用户模型。 这是我的两个想法两个实现:

- 第一种情况是在文章模型中定义一个名为add_comment的方法(用户,评论)

class ArticleModel(models.Model):
    ...
    def add_comment(self, user, comment):
        # Here I instantiate a new Comment object asociated to this article (self), the passed user and comment as parameter, and then save it.

- 第二种情况是在用户模型中定义一个名为comment_article的方法(文章,评论):

class UserModel(models.Model):
    ...
    def comment_article(self, article, comment):
        # Here I instantiate a new Comment object asociated to this user (self), the passed article and comment as parameter, and then save it.

在这些情况下,哪一个是实现良好面向对象的最佳实践?

1 个答案:

答案 0 :(得分:0)

enter link description here上,他们提到松散耦合

  

除非绝对必要,否则框架的各个层面不应相互“了解”。

这可以应用于您的模型。在这种情况下,我认为你的ArticleModel应该处理它与UserModel的关系,因为用户是一个可以(而且应该)没有其他模型的东西,但是对于那些有用户评论的文章也不能说。

相关问题