我有以下代码:
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排在第一位(它具有9月7日创建的最新Model2对象)。 另外,我可以更改以获得相同的结果吗?
答案 0 :(得分:0)
您可以使用类似这样的内容:
tax_lvl_n_attr
在此代码中,Model1.objects.all().order_by('-model2__created')
是model2
的{{1}},默认情况下是类名。