【问题标题】:Sorting related records in recursive relation以递归关系对相关记录进行排序
【发布时间】:2011-04-29 07:07:10
【问题描述】:

我有以下带有递归外键的课程。问题和答案存储在同一张表中。
问题,类型='q'
答案类型 = 'a'

我想在 DESC 中按日期对问题进行排序,因为依赖答案必须按 ASC 顺序排序。在 Django 中我该怎么做?

class Talk(models.Model):
    user = models.ForeignKey(User)
    destination = models.ForeignKey(Destination)
    text = models.TextField()
    type = models.CharField(max_length=30)
    sup = models.ForeignKey('self', blank=True, null=True, related_name='child')
    created_dt = models.DateTimeField(auto_now_add=True)
    thumb_up = models.IntegerField()
    thumb_down = models.IntegerField()

class Meta:
        ordering = ["-created_dt"] 

【问题讨论】:

    标签: django model


    【解决方案1】:
    questions = Talk.objects.filter(type='q')
    

    以默认顺序为您解答所有问题。要获得针对特定问题排序的答案,假设是最新的,请使用order_by

    question = questions[0]
    
    sorted_answers = Talk.objects.filter(sup=question).order_by('created_dt')
    

    question.child.order_by('created_dt')
    

    这看起来很有趣,因为您使用了 related_name

    【讨论】:

    • 这似乎有效,我有 {% for talk_child in talk.child.all %} 在视图中。似乎 talk.child.order_by('created_dt') 在视图中不受支持。有什么办法吗?
    猜你喜欢
    • 1970-01-01
    • 2016-08-14
    • 2014-03-08
    • 2014-03-04
    • 1970-01-01
    • 1970-01-01
    • 2015-03-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多