开发者

Sorting related records in recursive relation

开发者 https://www.devze.com 2023-03-01 06:32 出处:网络
I have following class with recursive foreign key. Questions and Answers storing in same table. Question, type=\'q\'

I have following class with recursive foreign key. Questions and Answers storing in same table.

Question, type='q'

Answer type = 'a'

I wan tot sort questions by date in DESC, where as dependent answer has to be sorte开发者_如何学Cd in ASC order. How can I do in 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"] 


questions = Talk.objects.filter(type='q')

gets you all the question in your default ordering. To get the answers sorted for a specific question, lets say the newest one, use order_by:

question = questions[0]

sorted_answers = Talk.objects.filter(sup=question).order_by('created_dt')

or

question.child.order_by('created_dt')

Which looks funny because of what you used for your related_name

0

精彩评论

暂无评论...
验证码 换一张
取 消