简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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