【发布时间】:2020-11-02 14:03:32
【问题描述】:
我有以下代码:
from django.db import Models
class Model1(models.Model):
#Attributes...
class Model2(models.Model):
model1_foreign_key = models.ForeignKey(Model1, related_name='some_name', on_delete=models.CASCADE)
created = models.DateTimeField(auto_now_add=True)
我的目标是通过最新创建的外键来订购第一项。例如:
Today is September eighth
Model A is an instance of Model1 and has two models related to it via the foreign key, model B (created on September 5th) and model C (created on September 6th). Assume times don't matter here.
Model D is an instance of Model1 and has another two models related to it via a foreign key, E and F (Created on September 5th and 7th respectively).
如果可以访问 Model1 的对象列表,例如 Model1.objects.all,我如何订购模型以使模型 D 先出现(它具有最新的 Model2 对象,创建于 9 月 7 日)。 或者,我可以改变什么来获得相同的结果?
【问题讨论】:
标签: python django django-models