我应该使用基于类或基于函数的视图吗?

时间:2016-07-19 20:01:22

标签: python django

这将是一个很长的帖子,所以请耐心等待。我想我已经意识到我必须重新编写我之前在模型中编写的大量代码。

我的模型看起来像这样:

class Word(models.Model):
    '''Word table for word, and frequency data'''

    language = models.ForeignKey(Language)
    name = models.CharField(max_length=50)
    frequency = models.IntegerField(default=0)
    rank = models.IntegerField(default=0)


    def __unicode__(self):
        value = u'%s' % (self.name)
        return value


    def wn_lookup(self):
        '''Calls the wordnet CLI for self'''    
        ...breaks up the output and returns the definitions as a list of tuples

    def wiktionary_lookup(self, wiktionary_prefix, driver):
        ...looks up the definition of the word on wiktionary
           returns data as a list

    def define(self, driver, choice, ask_input):
        ...Prints out a lot of options and asks the user to choose 
           what they want as a definition

           It then creates objects and calls other methods on a 
           subsequent definitions model

请注意,最后一个方法创建并调用后续定义模型的方法。

我有一些模型,所有模型都需要大量用户输入才能使数据输入半自动化。我相信我做的很愚蠢,我应该在视图中添加它们,但我对如何做到这一点感到有点困惑。

  1. 我应该使用基于类或基于功能的视图吗?
  2. 我想我必须为所有这些视图编写表单和模板吗?
  3. 我是否可能将所有内容(在模型中)保留在视图中?

1 个答案:

答案 0 :(得分:2)

  1. 您可以使用您想要的内容,Class Based Views的好处是继承。您可以扩展基础View类并在整个项目中使用它。此外,使用Generic Class Based Views进行操作的速度非常快。

  2. 是的,您应该为此模型编写表单,以提供用户输入。 Django为表单提供了快捷方式,可以根据模型保存数据。 Model Forms会使用等效的表单字段自动映射模型中的所有字段。

  3. Django遵循一个名为Fat Models的模式,因此在模型定义中存储模型的操作是完全正确的。