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?
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With