I'm currently working on a functionality in my web app, There is a form for users to upload images and when there's more than one images, i'm looping through the images to save each to the db.
The Property Model:
class PostProperty(models.Model):
poster = models.ForeignKey(User, on_delete=models.CASCADE)
publish = models.BooleanField(default=False)
title = models.CharField(max_length=300)
category = models.CharField(choices=CategoryTypes.choices, default= CategoryTypes.FOR_RENT, max_length=50)
category_type = models.ForeignKey(PropertyTypes,on_delete=models.CASCADE)
Then i have another model which is linked to the property model which allows users to upload images for the property on another page:
class PostPictures(models.Model):
post = models.ForeignKey(PostProperty, on_delete=models.CASCADE)
pictures = models.ImageField(default='property_post.jpg', upload_to='images/')
Have created a view function, which gets the images from the form and compresses it, after compression, it loops through each and saves it to the db.
memory_upload = []
for x in range(len(images)):
img = images[x]
im = Image.open(img)
im_io = BytesIO()
if im.mode != 'RGB':
im = im.convert('RGB')
im = im.resize(img_res)
im.save(im_io, format= 'JPEG', optimize=True, quality=50)
memory_upload.append(InMemoryUploadedFile(im_io, None, img.name, 'image/jpeg', im_io.tell(), None ))
for items in memory_upload:
parser = PostPictures.objects.create(post = property, pictures = items)
parser.save()
return redirect('profile')
After the images are saved in the db. I want to create a view for the property list where the user can see all the properties they've posted with only a single image being returned out of the list of images for the property, how do i go about it?.
CodePudding user response:
I think have figured it out but might not be the best implementation, if you have a better implementation for it, i would appreciate your answer.
lister = PostProperty.objects.filter(poster = request.user)
pix = []
for items in lister:
pics = PostPictures.objects.filter(post__title = items)
pix.append(pics[0])
context = {
'lister':lister,
'pix':pix,
}
This pushes the first value of the iteration and it also carries the properties of the linked model with it
CodePudding user response:
Try this, you can directly query this
PostPictures.objects.filter(post__poster=request.user)