Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django - "QuerySet' object has no attribute 'user'

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?

like image 537
avatar Avatar asked Oct 24 '11 21:10

avatar


2 Answers

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)
like image 144
Bernhard Vallant Avatar answered Sep 21 '22 23:09

Bernhard Vallant


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.

like image 23
shaunc Avatar answered Sep 19 '22 23:09

shaunc