0

模型的结构是我将 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 模板中排序我尝试了很多但没有找到解决方案,

提前致谢!!

4

1 回答 1

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')
于 2014-09-17T07:16:41.313 回答