【问题标题】:Count TextField characters with Django用 Django 计算 TextField 字符数
【发布时间】:2018-10-16 07:36:52
【问题描述】:

我已经使用 Python3.6 创建了 this simple counter,我想在我的模型中使用 TextField 做同样的事情。

我感兴趣的是第 37 行,即here;我想在 Django 中传输它。

class Post(models.Model):
    title = models.CharField(max_length=70, help_text="Write post title here. The title must be have max 70 characters", verbose_name="Titolo", unique=True)
    slug = models.SlugField(verbose_name="Slug", unique="True", help_text="Slug is a field in autocomplete mode, but if you want you can modify its contents")
    tagline = models.TextField(max_length=200, help_text="Write a post short description here. The description must be have max 200 characters", verbose_name="Breve descrizione dell'articolo")
    contents = models.TextField(help_text="Write your post here", verbose_name="Contenuti")
    time_of_reading = models.IntegerField(count(contents) / 250)
    highlighted = models.BooleanField(default=False, help_text="If you want that the post went be highlighted, click on this area", verbose_name="Articolo in evidenza")

    def __str__(self):
        return self.title

有了这个我有这个错误:

  File "/var/www/html/dev/miosito/django/v2.1/versions/aproject/muletto/models.py", line 4, in <module>
    class Post(models.Model):
  File "/var/www/html/dev/miosito/django/v2.1/versions/aproject/muletto/models.py", line 10, in Post
    time_of_reading = models.IntegerField(count(contents) / 250)

NameError: name 'count' is not defined

我是开发领域的新手

【问题讨论】:

  • 你从哪里得到这个? models.TextField 有计数功能吗?我建议如果你是新手,你应该坚持基本概念。这就是说这是更大的问题 imo... 为什么要在随时可以轻松计算的字段上浪费空间?我建议您阅读有关数据库规范化的内容以及为什么存储此类字段不是一个好主意。
  • 感谢您的建议。我认为可以用 javascript 做同样的事情。

标签: django-models python-3.6 counting django-2.1


【解决方案1】:

一种可能性是覆盖方法 save()。 在 save() 中做这样的事情:

    self.thistime_of_reading = self.count(self.contents)

这里: Django. Override save for model

【讨论】:

  • 我必须在模型帖子中添加这样的东西吗? ` def save(self): self.thistime_of_reading = count(self.contents)/250 ` 如果是,我有这个错误:` File "/var/www/html/dev/miosito/django/v2.1/versions/ aproject/muletto/models.py”,第 4 行,在 类帖子(models.Model)中:文件“/var/www/html/dev/miosito/django/v2.1/versions/aproject/muletto/models .py",第 9 行,在 Post time_of_reading = models.IntegerField(count(contents) / 250) NameError: name 'count' is not defined`
  • 你必须定义,也许在模型中,函数计数,并在保存方法中调用它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多