0

I'm creating a UserProfile model where users can add as many or as few images to their profile as they wish. I've considered using an Image model like so:

class Image(models.Model):
    related_profile = models.ForeignKey(UserProfile) # UserProfile is the name of the model class
    user_picture = models.ImageField(upload_to=get_user_img, blank=True, null=True, height_field='height_field', width_field='width_field')

When somebody visits their UserProfile then all of their Image objects will be displayed; however when I want to edit the UserProfile (i.e. delete an image or two) but am unable to do this. The 'instance' doesn't want to return more than one Image object to edit as I get error:

get() returned more than one Image -- it returned 2!

There's a similar question like this which suggested filter() as opposed to get() here django - get() returned more than one topic though this uses a ManyToMany relationship, and the solution didn't work for my error.

Does anybody know any good ways to restructure this so that I can edit each model object from the same page (so not returning the aforementioned error)?

Like the title suggests, I'm wondering if it's possible to store a set of images as a list within one field of the UserProfile model because that's a potential idea.

Community
  • 1
  • 1
jayt
  • 758
  • 1
  • 14
  • 32

1 Answers1

0

You are on the right track. The Model.objects.get() method expects the query result to be one row (instance), which is then returned. However in your case the UserProfile can have any number of related Image's. So you need to iterate through the (possibly) multiple results you are going to get back from your query, and do something with each one. More like:

# there is only ONE UserProfile per userid.. that is to say, userid is a 
# unique key.. so I can use get() to fetch it

profile = UserProfile.objects.get(userid=the_userid)

# now I need to get each image
for image in Image.objects.filter(user_profile=profile):
    # do something with image....

If you only need the Image instances and don't need the UserProfile instance, then you can shorten this with a join:

for image in Image.objects.filter(user_profile__userid=the_userid):
    # do something with image....

I should add that this has nothing to do with images, but applies any time you fetch data from the database using Django. Any query that has multiple rows needs to be done in this way.

little_birdie
  • 5,600
  • 3
  • 23
  • 28