Answer the question
In order to leave comments, you need to log in
How to generate a list of files from a queryset?
I want to check for files already attached to the post before saving the added photos.
I get the list of files through Image.objects.filter(). The output is an object of type Image. I need to place a list of file names in a variable for later verification.
Image model (linked to posts):
class Image(models.Model):
article = models.ForeignKey(Article, on_delete=models.CASCADE, related_name='images', null=True, blank=True)
file = models.ImageField('Файл', upload_to='uploads/', default="/no-image.png", storage=MediaFileStorage(), unique=False)
@property
def filename(self):
return self.file.name.rsplit('/', 1)[-1]
...
edit_post = get_object_or_404(Article, slug=slug)
post_gallery = Image.objects.filter(article_id=edit_post.pk).values('file') # <QuerySet [{'file': 'uploads/oikos_spanish-brush.jpg'}]>
print((post_gallery))
...
if post_form.is_valid():
#Create, but don't save the post
edit_post = post_form.save(commit=False)
#instance = Article.objects.get(pk=edit_post.pk)
for f in request.FILES.getlist('files'):
if post_gallery and f in post_gallery: # <-------- тут надо изменить проверку
print('file exist')
else:
image_object = Image(file=f, article=edit_post)
image_object.save()
edit_post.save()
Answer the question
In order to leave comments, you need to log in
In general, I had to add a new name field to the Image model and then everything became easier.
Thanks for the tip Dr. Bacon
Total:
post_gallery = Image.objects.filter(article_id=edit_post.pk)
gallery_file_list = post_gallery.values_list('name', flat=True)
...
for f in request.FILES.getlist('files'):
file = f.name
if post_gallery and file in gallery_file_list:
print('file exist')
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question