开发者

search with related_name Django

I have such models:

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

class Interest开发者_如何学运维s(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

How to write search filter with DjangoORM for such query (for example):

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

Thanks in advance!!!


I think you can try this:

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

But everything is well explained here : django doc on queries


To specify a field that's in a related model you need to use double underscores

so life_goals_name should be life_goals__name

There's your problem :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜