从Python Crash课程中练习:练习18-2

时间:2016-05-13 10:01:05

标签: python django-admin

关于这个主题的章节没有提供如何做的例子。我希望有人可以根据我提供的内容推断它,或者可能会幸运,有人读过可以提供帮助的书。

这是exerpt:&#34;练习18-2。短条目:当Django在管理站点或shell中显示时,Entry模型中的using Newtonsoft.Json; .... [NotMapped] public Dictionary<string, string> MetaData { get; set; } = new Dictionary<string, string>(); /// <summary> <see cref="MetaData"/> for database persistence. </summary> [Obsolete("Only for Persistence by EntityFramework")] public string MetaDataJsonForDb { get { return MetaData == null || !MetaData.Any() ? null : JsonConvert.SerializeObject(MetaData); } set { if (string.IsNullOrWhiteSpace(value)) MetaData.Clear(); else MetaData = JsonConvert.DeserializeObject<Dictionary<string, string>>(value); } } ()方法当前将省略号附加到Entry的每个实例。向__str__方法添加if语句,仅当条目长度超过50个字符时才添加省略号。使用管理站点添加长度少于50个字符的条目,并检查它在查看时没有省略号。&#34;

代码块位于底部:

__str__()

2 个答案:

答案 0 :(得分:0)

更改from django.db import models class Entry(models.Model): """Something specific learned about a topic.""" topic = models.ForeignKey(Topic) text = models.TextField() date_added = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = 'entries' def __str__(self): """Return a string representation of the model.""" return self.text[:50] + ("..." if len(self.text) > 50 else "") 的定义非常简单:

cell.label.text = indexPath.row + 1

答案 1 :(得分:0)

from django.db import models

class Entry(models.Model):
    """Something specific learned about a topic."""
    topic = models.ForeignKey(Topic, on_delete=models.CASCADE)
    text = models.TextField()
    date_added = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name_plural = 'entries'

    def __str__(self):
        """Return a string representation of the model."""
        if len(self.text) > 50:
            return f"{self.text[:50]}..."
        else:
            return f"{self.text}"