2017-05-23 88 views
0

我的模型看起來是這樣的: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__range。如何獲得該日期範圍內每個人的最後一張紙條,並符合其他標準?

回答

1
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() 

將返回查詢集

或最遲在字段名的最後一個對象

Note.objects.filter(query).exclude(~Q(owner=request.user)).values('owner', 'action', 'person').latest('field_name') 
+0

非常感謝。從我所能看到的情況來看,這隻會返回最後一個對象。我想獲得每個人的最後一個對象。 因此類似於: 'Select * from note where date_added between now和fourteen_days_ago GROUP BY'person'' –

+0

@ 5h3z4n查看https://docs.djangoproject.com/zh/1/11/topics/db/聚合/ –

+0

@ pawel.ad這看起來像我需要!謝謝 –