在这个模型中:
class Rank(models.Model):
User = models.ForeignKey(User)
Rank = models.ForeignKey(RankStructure)
date_promoted = models.DateField()
def __str__(self):
return self.Rank.Name.order_by('promotion__date_promoted').latest()
我收到错误:
Exception Value:
'str' object has no attribute 'order_by'
我希望最新的Rank为默认值。我该如何设置?
感谢。
更新#1
添加了排名结构
class RankStructure(models.Model):
RankID = models.CharField(max_length=4)
SName = models.CharField(max_length=5)
Name = models.CharField(max_length=125)
LongName = models.CharField(max_length=512)
GENRE_CHOICES = (
('TOS', 'The Original Series'),
('TMP', 'The Motion Picture'),
('TNG', 'The Next Generation'),
('DS9', 'Deep Space Nine'),
('VOY', 'VOYAGER'),
('FUT', 'FUTURE'),
('KTM', 'KELVIN TIMELINE')
)
Genre = models.CharField(max_length=3, choices=GENRE_CHOICES)
SPECIALTY_OPTIONS = (
('CMD', 'Command'),
('OPS', 'Operations'),
('SCI', 'Science'),
('MED', 'Medical'),
('ENG', 'Engineering'),
('MAR', 'Marine'),
('FLT', 'Flight Officer'),
)
Specialty = models.CharField(max_length=25, choices=SPECIALTY_OPTIONS)
image = models.FileField(upload_to=image_upload_handler, blank=True)
这是Class Rank中Rank引用的Rank_structure。 用户外键进入标准用户表。
答案 0 :(得分:0)
您收到错误的原因是self.Rank.Name
不是ModelManager
,您可以在其上调用order_by
。如果您想拨打objects
,那么您需要在某处order_by
。我们无法帮助您使用所需查询的django格式,除非您还按照多个评论者的要求发布模型定义。也就是说,我怀疑你想要的是:
def __str__(self):
return self.objects.filter(Rank_id=self.Rank_id).order_by('date_promoted').latest().User.Name