关于这个主题的章节没有提供如何做的例子。我希望有人可以根据我提供的内容推断它,或者可能会幸运,有人读过可以提供帮助的书。
这是exerpt:"练习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__()
答案 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}"