Home > Net >  Query using related name in django
Query using related name in django

Time:08-05

I've two models:

class User(models.Model):
    email = models.EmailField()
    name = models.CharField(max_length=255)
    password = models.CharField(max_length=255)

class Profile(models.Model):
    group = models.ForeignKey(User, related_name='profiles')
    image = models.ForeignKey(Media, on_delete=models.CASCADE)
    #more attributes

I've user's id and I want to get his image.

user = User.objects.get(id=id)
image = user.profiles.image

This is throwing error. How can I do it?

CodePudding user response:

The reason for the error is that your User to Profile relation is many-to-one, so when you call user.profiles it is creating a queryset of possibly many Profile objects and not just one. The queryset of profiles does not have an image attribute.

You need to do one of two things, either:

a) Extract a single profile from your profiles queryset, e.g. user.profiles.first() - note that if you have multiple profiles then this will just get the first one in the set by whichever order_by the profile model has.

b) Set the User/Profile relationship to one-to-one rather than many-to-one by using a models.OneToOneField. This will allow you to directly access the profile with user.profile

Once you have direct access to the profile object, you can call the image attribute that it has.

  • Related