S
S
Stanislav Shabalin2020-08-31 11:43:51
Django
Stanislav Shabalin, 2020-08-31 11:43:51

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]


View (where I edit the Article post and add a photo to the Image table with reference to the current post):
I tried to select records using values('file'), but I can't form a list of names without subdirectories.
And in the case of values_list('filename', flat=True) - Django swears at all

...
    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()


Please tell me how to get the correct list for checking the if f in post_gallery condition:

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Stanislav Shabalin, 2020-08-31
@Starck43

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')

Maybe someone will come in handy!

D
Dr. Bacon, 2020-08-31
@bacon

You need to check by content, not by name.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question