简体   繁体   English

Django ORM-筛选器相关对象

[英]Django ORM - Filter Related Objects

I apologize if this is a duplicate, but I was unable to find any other SO posts that address this matter. 很抱歉,如果这是重复的,但是我找不到任何其他SO帖子可以解决此问题。 I have models like so: 我有这样的模型:

class Person(models.Model):
    pass

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

I know that I can find all people who have cool interests like so: 我知道我可以找到所有有很强兴趣的人,例如:

Person.objects.filter(interests__is_cool=True)

However, what I really want is to get only their cool interests when I get the Person object. 但是,我真正想要的是在获得Person对象时仅获得他们的酷兴趣。 I know that I could always pluck the related queryset out and operate on it, like so: 我知道我总是可以选择相关的查询集并对其进行操作,如下所示:

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

but I cannot assign it back to the person instance since the relationship is reversed. 但由于关系相反,因此我无法将其分配回个人实例。 To summarize, the goal is to use the ORM directly to filter the Interest objects being returned in the person.interests queryset. 总而言之,目标是直接使用ORM来过滤person.interests集中返回的Interest对象。

One possibility is to define a method or property on the model: 一种可能性是在模型上定义方法或属性:

def cool_interests(self):
    return self.interests.filter(is_cool=True)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM