Django ORM过滤

时间:2017-05-23 10:44:08

标签: python django django-orm

我的模型看起来像这样:

Person(model.Models):
    name = model.CharField(max_length=32)
    date_added = models.DateTimeField(auto_now_add=True)

Note(model.Models):
    person = model.ForeignKey(Person)
    action = model.CharField(max_length=32, default='call)
    date_added = models.DateTimeField(auto_now_add=True)
    owner = model.ForeignKey(User)

我的观点:

def get_working_persons(self):
    relevant_actions = ['call', 'meeting', ...]
    query = Q(action__in=relevant_note_actions) | Q(date_added__range=[fourteen_days_ago, now])
    get_current_person_notes = Note.objects.filter(query).exclude(~Q(owner=request.user)).values('owner', 'action', 'person')

这将返回一个笔记列表,其中每个人都列出了所有笔记,这些笔记都发布在date_added__范围内。如何获得该日期范围内符合其他标准的每个人的最后一个注释?

1 个答案:

答案 0 :(得分:1)

Tabs

将返回查询集的顶级对象 或

Note.objects.filter(query).exclude(~Q(owner=request.user)).values('owner', 'action', 'person').first()

将返回查询集的最后一个对象

或最新的字段名称

Note.objects.filter(query).exclude(~Q(owner=request.user)).values('owner', 'action', 'person').last()