Vitalii Ponomar
Vitalii Ponomar

Reputation: 10946

search with related_name Django

I have such 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

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!!!

Upvotes: 0

Views: 3326

Answers (2)

Jack
Jack

Reputation: 41

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 :)

Upvotes: 2

mogo
mogo

Reputation: 440

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

Upvotes: 4

Related Questions