Django查询在另一个表中有结果的对象

时间:2015-11-26 20:29:21

标签: django django-models

models.py

class Event(models.Model):
    name = models.CharField(max_length=100)
    date = models.DateField()

class Result(models.Model):
    event = models.ForeignKey(Event)
    place = models.IntegerField()
    person = models.CharField(max_length=100)
    gender = models.CharField(max_length=1)
    score = models.IntegerField()

事件样本数据:

id, name, date
1, 'event1', '2015-01-01'
2, 'event2', '2015-02-01'
3, 'event3', '2015-03-01'

结果样本数据:

event_id, place, person, gender, score
1, 1, 'al', 'M', 25
1, 2, 'bob', 'M', 22
1, 3, 'cindy', 'F', 21
1, 4, 'doug', 'M', 20
2, 1, 'elen', 'F', 30
2, 2, 'frank', 'M', 28
2, 3, 'gord', 'M', 20
2, 4, 'helen', 'F', 19

我想选择Event中的所有对象,其中该事件的Result中至少有一个结果。

我现在怎么做:

events = Event.objects.all().order_by('-date')
eventswithresults = []    
for event in events:
    count = Result.objects.filter(event_id=event).count()
    if count > 0:
        eventwithresults.append(event)

必须有一种djangoier方式。

1 个答案:

答案 0 :(得分:4)

你可以这样做:

from django.db.models import Count
events = Event.objects.annotate(num_eve=Count('result')).filter(num_eve__gte=1)