模型的结构是我使用hvad进行多语言
class Course(TranslatableModel):
translations = TranslatedFields(
domain = models.ForeignKey('domain.Domain'),
#track = models.ForeignKey('track.Track'),
track = models.ForeignKey('track.Track', blank=True, null=True),
course_nm = models.CharField(max_length=100, verbose_name =_('Course Name')),
nature_of_training = models.TextField(verbose_name = _('Nature of Training')),
duration = models.PositiveIntegerField(verbose_name =_('Duration')),
sem = models.PositiveIntegerField(verbose_name =_('Semester')),
degree_level = models.CharField(max_length=100, verbose_name =_('Degree Level')),
credit = models.PositiveIntegerField(verbose_name =_('Credits')),
locations = models.CharField(max_length=100, verbose_name =_('Locations')),
accessible = models.CharField(max_length=100, verbose_name =_('Accessible')),
des = models.TextField(verbose_name = _('Description')),
admission_details = models.TextField(verbose_name = _('Admission Details')),
further_study_details = models.TextField(verbose_name = _('Further Study Details')),
seats = models.PositiveIntegerField(verbose_name =_('Seats')),
title = models.CharField(max_length=512, verbose_name=_('Title')),
slug = models.SlugField(max_length=512, verbose_name=_('Slug')),
created_date = models.DateTimeField(auto_now_add=True, blank=True, null=True),
updated_date = models.DateTimeField(auto_now=True, blank=True, null=True),
created_by = models.ForeignKey(User, blank=True, null=True, editable=False),
)
在上下文中将对象从视图传递到模板以进行排序我应用了这个,
在views.py中我只是在上下文中传递对象
def get_context_data(self, **kwargs):
context = super(DegreeDetailView, self).get_context_data(**kwargs)
context['courses'] = Course.objects.all()
return context
模板中的
{% for c in courses|dictsort:"track" %}
{% if c.domain|stringformat:"s" == d.domain_nm %}
{% if c.track != None %}
<h3>{{ c.track }}</h3>
{% endif %}
{{ c.course_nm }}
{% endif %}
{% endfor %}
但每次结果更改后刷新页面
所以我应该做什么来在django模板中进行排序,或者任何替代方案都可以在django模板中进行排序 我尝试了很多,但找不到解决方案,
先谢谢!!
答案 0 :(得分:0)
我认为,原因,为什么会得到不同的结果,是因为track
可以是null
:
track = models.ForeignKey('track.Track', blank=True, null=True),
因此,track
字段设置为null
的课程将没有确切的顺序,因此它们将以随机位置呈现。因此,您需要将所有track
字段设置为某个值(并可能删除blank=True, null=True
+应用迁移),或者按其他字段排序。
此外,在模板中使用dictsort
排序模型不是最好的方法。最好在数据库级别执行此操作,为查询集提供order_by
:
context['courses'] = Course.objects.all().order_by('track__id')