繁体   English   中英

过滤 Django 中的多个数据

[英]Filtering multiple data in Django

我想根据下面的data值检索多个值。 目前我所做的是我一直在使用下面for loop ,但它只检索一个值,我想根据looping result进行更新。如果有人能弄清楚我在哪里做错了,那就太好了。 非常感谢你

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

在此处输入图像描述

在此处输入图像描述

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

模型.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)

你可以这样试试。 values_list返回photos array ,您可以将其用于过滤in更新所有这些。 print以进行调试检查更新前获得的内容,如果不使用可以删除。

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

你应该试试django-filter package。 它支持单个查询中的多个过滤器。

您还可以使用Imagine 智能编译器,该编译器将为您的应用程序生成代码,包括这个多字段过滤器。 它还将简化您的权限检查代码。 您的 model 非常简单,您不必做任何自定义操作。 整个代码库和测试应该可以使用 Imagine 编译器生成。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM