如何查询多个对象Django 1.8的多个外键相关对象

时间:2017-01-19 17:32:40

标签: django

无法弄清楚如何查询多个对象的多个外键相关对象。 模态:

class Notification(models.Model):
    who_did = models.ForeignKey('UserProfile', related_name='who_did_NOTIFICATION', blank=True)

观。对象很好:

objects = Notification.objects.all()
profiles = objects.select_related('who_did').all()

也尝试过:

profiles = objects.prefetch_related().all()

profiles = objects.select_related.all()

如何在Django 1.8中正确处理它?<​​/ p>

1 个答案:

答案 0 :(得分:0)

ids = [123, 456, 789]

qs = Notification.objects.filter(id__in=ids)
for o in qs:
    print(o.id)
    for n in o.who_did_NOTIFICATION.all():    
        print("*", n.id)