我有两种模式:模式和类别。
class Pattern(models.Model):
name = models.CharField(max_length=255, default=u'')
categories = models.ManyToManyField(Category, related_name='patterns')
def __unicode__(self):
return u"{}".format(self.name)
class Category(models.Model):
name = models.CharField(max_length=255, default=u'')
def __unicode__(self):
return u"{}".format(self.name)
我需要检查valid
中的每个模式是否已经存在,并正确修改其多个<some_pattern>.categories
字段。
现在我按照以下方式执行此操作(valid
是模式列表,categories
是某些类别的查询集):
for pattern in valid:
obj, created = Pattern.objects.get_or_create(name=pattern)
if created:
obj.categories = categories
else:
obj.categories.add(*categories)
如何使用尽可能少的SQL查询来做同样的事情?
答案 0 :(得分:0)
所以解决方案如下:
# finding out patterns that not exist in database and creating them
exist = Pattern.objects.filter(name__in=valid)
Pattern.objects.bulk_create([Pattern(name=p) for p in valid if p not in [unicode(pat) for pat in exist]])
# creating new relations
patterns_to_set_category = Pattern.objects.filter(name__in=valid)
relations_to_create = list()
for category in categories:
for pattern in patterns_to_set_category:
relations_to_create.append(Pattern.categories.through(pattern=pattern, category=category))
Pattern.categories.through.objects.bulk_create(relations_to_create)