gpt4 book ai didi

python - 更新多对多关系

转载 作者:行者123 更新时间:2023-11-28 18:12:44 24 4
gpt4 key购买 nike

我有 3 个模型(简化):

class Product(models.Model):
category = models.ForeignKey('Category', related_name='products', to_field='category_name')
brand = models.ForeignKey('Brand', related_name='products', to_field='brand_name')

class Brand(models.Model):
brand_name = models.CharField(max_length=50)
categories = models.ManyToManyField('Category', related_name='categories')

class Category(models.Model):
category_name = models.CharField(max_length=128)

我想将管理中的一个类别更改为一堆产品,我为此编写了一个自定义管理功能。之后,我需要更新 Brand-Categories 多对多关系,以检查该 Category 是否仍可用于特定 Brand。我写了这个函数:

def brand_refresh():
brands = Brand.objects.all().prefetch_related('shops', 'categories')
products = Product.objects.select_related('shop', 'brand', 'category')

for brand in list(brands):
for category in brand.categories.all():
if not products.filter(category=category).exists():
brand.categories.remove(category)

for product in list(products.filter(brand=brand).distinct('category')):
if product.category not in [None, category]:
brand.categories.add(product.category)

在我看来,这个怪物正在运行,但循环所有周期需要 2 个小时(我有约 22 万个产品、4 千多个品牌和约 500 个类别)。 这里有更新 M2M 关系的更好方法吗?我认为 .prefetch_related() 应该在这里有所帮助,但我现在所拥有的似乎没有效果。

最佳答案

这是循环第一部分的解决方案:

您应该在数据库的一次性本地副本上尝试此操作,并在生产中运行它们之前检查一切是否正常:

from django.db.models import Count

# get a list of all categories which have no products
empty_categories = Category.objects.annotate(product_count=Count('products')).filter(product_count=0).values_list('id', flat=True)

# delete association of empty categories in all brands
Brand.categories.through.objects.filter(category_id__in=list(empty_categories)).delete()

对于第二部分,也许你可以做这样的事情,但我不确定它是否更快(甚至是正确的):

for brand in Brand.objects.all():
# get a list of categories of all products in the brand
brand_product_categories = brand.products.all().value_list('category__id', flat=True).distinct()

# get the brand's categories
brand_categories = Category.objects.filter(category__brand=brand).value_list('id', flat=True)

# get elements from a not in b
categories_to_add = set(brand_product_categories) - set(brand_categories)

for category_id in categories_to_add:
brand.categories.add(category_id)

关于python - 更新多对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50255240/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com