用related_name Django搜索

时间:2011-10-08 05:50:05

标签: django django-models

我有这样的模特:

class LifeGoals(models.Model):
    name = models.CharField(max_length=200)

class Interests(models.Model):
    name = models.CharField(max_length=200)

class Sports(models.Model):
    name = models.CharField(max_length=200)

class UserProfile(models.Model):
    name = models.CharField(max_length=50)
    life_goals = models.ManyToManyField(LifeGoals, related_name='user_life_goals')
        # may be more than 1 choice
    interests = models.ManyToManyField(Interests, related_name='user_interests')
        # may be more than 1 choice
    sports = models.ManyToManyField(Sports, related_name='user_sports')
        # may be more than 1 choice

如何使用Django ORM编写搜索过滤器以进行此类查询(例如):

 User that has some options in LifeGoals and some options in Interests and some options in Sports

提前致谢!!!

2 个答案:

答案 0 :(得分:5)

我想你可以试试这个:

UserProfile.objects.filter(life_goals__name="goal_name",
                           interests__name="interests_name", 
                           sports__name="sports_name")

但是这里的一切都很好解释:django doc on queries

答案 1 :(得分:2)

要指定相关模型中的字段,您需要使用双下划线

所以life_goals_name应为life_goals__name

你的问题是:)