8

I have two models Profile and Avatar.

models.py

class Profile(models.Model):
    user = models.ForeignKey(User)
    profile_name = models.CharField(blank=True, max_length=50)

    def __unicode__(self):
       return u'%s %s' % (self.user, self.profile_name)  


class Avatar(models.Model):
    user = models.ForeignKey(User)
    paths = models.CharField(max_length=100)
    def __unicode__(self):
        return u'%s %s' % (self.user,self.paths)

I want to do a seach on the profile_name field (from Profile model) and get the paths to the pictures stored on the field paths (from the Avatar model).

view.py

profile_name_search = Profile.objects.filter(profile_name=usr_name)
user_avatar = Avatar.objects.filter(user=profile_name_search.user.id)

usr_name variable is passed from a form filed.

For some reason I'm getting this error:

'QuerySet' object has no attribute 'user'
user_avatar = Avatar.objects.filter(user=profile_name_search.user.id)

Any ides?

2 Answers 2

21

filter() returns a QuerySet also if only one object if found. If you want to return just a model instance, use get():

profile_name_search = Profile.objects.get(profile_name=usr_name)
user_avatar = Avatar.objects.filter(user=profile_name_search.user.pk)
Sign up to request clarification or add additional context in comments.

2 Comments

What if the profile_name_search returns multiple user names? For example I want to return all the user names that are like usr_name like this: profile_name_search = Profile.objects.filter(profile_name__contains=usr_name)
If you expect more than one to be returned use filter(). If you use get() and more than one instance is found, the exception MultipleObjectsReturned will be raised. See the django documentation
1

Remember that "filter" returns a query not a model. Is profile name search supposed to return possibly multiple users? If so, I think you want:

users = User.objects.filter( profile_set__profile_name = usr_name )
user_avatar = Avatar.objects.filter( user__in = users )

Otherwise you may want:

profile = Profile.objects.get( profile_name = usr_name )
avatars = profile.avatar_set.all()

If there is only one avatar per user you can use a OneToOneField from Avatar to profile, and then just access as profile.avatar.

1 Comment

What I realized is that for my application would be more helpful if I could get all the users that have user name "like" usr_name. So instead of just one user what if I get multiple records/users back. So instead of I wrote above I have this: profile_name_search = Profile.objects.filter(profile_name__contains=usr_name) . How would I get the avatar for every user in this case?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.