我有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)
我希望在管理员界面中将一个分类更改为一组产品,我已经编写了一个自定义的管理员函数来完成这个操作。之后,我需要更新品牌-分类
多对多关系,以检查特定的品牌
是否仍然可以使用该分类
。我已经编写了以下函数:
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个小时(我有约220k个产品、4k+个品牌和约500个类别)。在这里更新M2M关系是否有更好的方法?我认为.prefetch_related()
应该对此有所帮助,但是现在似乎没有效果。