我想首先按 NoteReposter 模型(中介)的 date_added (日期时间)对备注对象进行排序,如果是的话null然后按注意模型本身的 date_created (DateTime)对其进行排序。
这是我目前在views.py
中所做的工作class Note(models.Model):
note = models.CharField(max_length=2100)
date_modified = models.DateTimeField(auto_now=True, blank=True)
# If the notereposter__date_added is null then sort it using this datetime field
date_created = models.DateTimeField(auto_now_add=True)
author = models.ForeignKey('NotepikUser',
related_name="%(class)ss_created")
reposters = models.ManyToManyField('NotepikUser', through="NoteReposter",
related_name="%(class)ss_reposted", blank=True)
categories = models.ManyToManyField('Category', blank=True,
related_name='notes')
在我的models.py
中注意型号
class NoteReposter(models.Model):
note = models.ForeignKey("Note", on_delete=models.CASCADE)
user = models.ForeignKey("NotepikUser", on_delete=models.CASCADE)
date_modified = models.DateTimeField(auto_now=True, blank=True)
# Sort by this datetime field first
date_added = models.DateTimeField(auto_now_add=True)
NoteReposter模型(中介)
someone created note1 (Note)
note1 date_created is 2016 January 1, 5:00 PM
User2 created note2
note2 date_created is 2016 January 1, 5:30 PM
User2 reposted note1 (note of someone)
notereposter1 (NoteReposter instance) created with user = User2,
note=note1, date_added = 2016 January 1, 6:00 PM
User2 created note3
note3 date_created is 2016 January 1, 6:30 PM
不幸的是我的解决方案没有正确排序
谢谢!
修改
<note3> 6:30 PM,
<notereposter1.note> 6:00pm
<note2> 5:30pm
我希望这些笔记按照这样排序
{{1}}
答案 0 :(得分:0)
我现在明白了。对于那些感兴趣的人,这是我的解决方案。
from django.db.models import DateTimeField, F, Case, When
notes.annotate(newest_in_vault=Case(When(notereposter__isnull=False,
then=F("notereposter__date_added")), default=F("date_created"),
output_field=DateTimeField()))
# Sort it now
notes = notes.order_by("-newest_in_vault")