Marie Loise
Marie Loise

Reputation: 107

Filtering multiple data in Django

I want to retrieve multiple value based on their data value below. Currently what I did is I've been using for loop below but it only retrieve one value and I want to update based on the looping result.It would be great if anybody could figure out where I am doing something wrong. thank you so much in advance

gallery_photos table. I want to update `Person tbl path when the value of photos column in gallery_photos and path person table equals

enter image description here

Person tbl

enter image description here

@login_required(login_url='log_permission')
def archive_folder(request):
    if request.method == 'POST':
        data_id = request.POST.get('id')  #single value only example we have: 6

        data = gallery_photos.objects.filter(gallery_info_id = idd) # multiple value example we have 3 rows

        for sample in data :
            viewing= sample.photos # I want to retrieve those three rows based on their photos column value in database
            Person.objects.filter(path = viewing).update(path=None)
    return JsonResponse({'data': 'success'})

models.py

class folder_info(models.Model):
     title = models.CharField(max_length=50,blank=True, null=True)
     date_upload = models.DateField(null=True, blank=True)
     class Meta:
         db_table = "folder_info"

class gallery_photos(models.Model):
    gallery_info_id = models.IntegerField()
    photos = models.FileField(upload_to='Photos/', unique=True)
    class Meta:
        managed = False
        db_table = 'gallery_photos'

class Person(models.Model):
    path = models.CharField(max_length=60,blank=True, null=True)

Upvotes: 0

Views: 1140

Answers (2)

imagine.ai
imagine.ai

Reputation: 1

You should try the django-filter package. It supports multiple filters in a single query.

You can also use the Imagine smart compiler that will generate the code for your app including this multiple-field filters. It will also simplify your permissions checking code. Your model is simple enough, that you should not have to do anything custom. The entire code base and tests should be generateable using the Imagine compiler.

Upvotes: 0

Ngoc Pham
Ngoc Pham

Reputation: 1458

You can try like this. values_list return array of photos, and you can use it for filter in for update all of this. print for debug check what you get before update, can remove if you don't use.

def archive_folder(request):
    if request.method == 'POST':
        data_id = request.POST.get('id')

        photos_data = gallery_photos.objects.filter(gallery_info_id = data_id).values_list("photos", flat=True)

        print(photos_data)
        Person.objects.filter(path__in = photos_data).update(path=None)
    return JsonResponse({'data': 'success'})

Upvotes: 2

Related Questions