【问题标题】:How to modify manytomany field for each object in a Queryset hitting the database as few as possible如何修改查询集中每个对象的多对多字段,尽可能少地访问数据库
【发布时间】:2014-10-21 04:41:45
【问题描述】:

我有两个模型:模式和类别。 模式有一个多态字段categories = models.ManyToManyField(Category, related_name='patterns')

我的视图从表单中获取类别的查询集。我需要获取标有该类别的所有模式,并从每个模式的 categories 字段中删除这些类别。

现在我这样做如下:

patterns_to_remove_category = Pattern.objects.all()
for category in categories:
    patterns_to_remove_category = patterns_to_remove_category.filter(categories=category)

for pattern in patterns_to_remove_category:
    pattern.categories = pattern.categories.exclude(pk__in=[c.pk for c in categories])

但我想尽量减少对数据库的点击次数。最好的方法是什么?

【问题讨论】:

    标签: django django-queryset django-orm


    【解决方案1】:

    我建议您使用隐式through 模型并像这样进行查询:

    Pattern.categories.through.objects.filter(category__in=categories).delete()
    

    【讨论】:

    • django shell 返回以下内容:
    • failed: django.db.utils.NotSupportedError: (1235, "This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'")
    • 你能发一个输出Pattern.categories.through.objects.filter(category__in=categories).all().query.__str__() 吗?
    • 或者,您可以将filter(category__in=categories) 替换为filter(category_pk__in=[c.pk for c in categories])
    • 谢谢!那行得通!我刚刚修改了查询,所以最后看起来像:Pattern.categories.through.objects.filter(category_id__in=[c.pk for c in categories]).delete()
    猜你喜欢
    • 1970-01-01
    • 2010-11-02
    • 1970-01-01
    • 2021-06-23
    • 1970-01-01
    • 1970-01-01
    • 2011-04-07
    • 1970-01-01
    • 2021-11-24
    相关资源
    最近更新 更多