Django ORM - 过滤相关对象

时间:2018-06-08 17:43:54

标签: python django django-models django-orm

如果这是重复,我道歉,但我无法找到解决此问题的任何其他SO帖子。我有这样的模型:

class Person(models.Model):
    pass

class Interest(models.Model):
    person = models.ForeignKey(Person, related_name='interests')
    is_cool = models.BooleanField()

我知道我可以找到所有喜欢这种兴趣的人:

Person.objects.filter(interests__is_cool=True)

但是,我真正想要的是在获得Person对象时只获得他们的兴趣。我知道我总是可以拔出相关的查询集并对其进行操作,如下所示:

interests = person.interests.filter(is_cool=True)

但我无法将其分配回人员实例,因为关系是相反的。总而言之,目标是直接使用ORM过滤Interest查询集中返回的person.interests个对象。

1 个答案:

答案 0 :(得分:2)

一种可能性是在模型上定义方法或属性:

if (global::System.Diagnostics.Debugger.IsAttached) 
    global::System.Diagnostics.Debugger.Break();    
相关问题