Django在查询OneToMany关系时如何保持秩序?

时间:2016-05-24 08:44:25

标签: django

两个模型(报告可能包含许多屏幕截图):

class Report(models.Model):
    ...

class Screenshot(models.Model):
    report = models.ForeignKey(Report, related_name='screenshots', on_delete=models.CASCADE)
    image = models.ImageField(upload_to="screenshots/%Y/")
    order = models.IntegerField()

    class meta:
        ordering = ['order'] # output the correct order

查询所有报告及其相关屏幕截图时:

reports = Report.objects.all()
for r in reports:
    screenshots = r.screenshots.all()
    for s in screenshots:
        print s.order  # output is out of order like 4,1,2,3

屏幕截图的顺序不会保留。

有没有更好的方法来进行这样的查询,但是保留了OneToMany关系的顺序?

0 个答案:

没有答案