Only loop through users once when saving static segments
When saving a new static segment we count the matching users and populate the segment from the database. Each of these requires us to loop through all of the users, so it's better to do them at the same time.
This commit is contained in:
@ -87,7 +87,7 @@ class SegmentAdminForm(WagtailAdminModelForm):
|
||||
if not self.instance.is_static:
|
||||
self.instance.count = 0
|
||||
|
||||
if is_new:
|
||||
if is_new and self.instance.is_static and not self.instance.all_rules_static:
|
||||
rules = [
|
||||
form.instance for formset in self.formsets.values()
|
||||
for form in formset
|
||||
@ -113,18 +113,20 @@ class SegmentAdminForm(WagtailAdminModelForm):
|
||||
User = get_user_model()
|
||||
users = User.objects.filter(is_active=True, is_staff=False)
|
||||
|
||||
take_user = takewhile(
|
||||
lambda x: instance.count == 0 or len(users_to_add) <= instance.count,
|
||||
users
|
||||
)
|
||||
for user in take_user:
|
||||
matched_count = 0
|
||||
for user in users.iterator():
|
||||
request.user = user
|
||||
passes = adapter._test_rules(instance.get_rules(), request, instance.match_any)
|
||||
if passes and instance.randomise_into_segment():
|
||||
users_to_add.append(user)
|
||||
elif passes:
|
||||
users_to_exclude.append(user)
|
||||
if passes:
|
||||
matched_count += 1
|
||||
if len(users_to_add) <= instance.count:
|
||||
if instance.randomise_into_segment():
|
||||
users_to_add.append(user)
|
||||
else:
|
||||
users_to_exclude.append(user)
|
||||
|
||||
instance.matched_users_count = matched_count
|
||||
instance.matched_count_updated_at = datetime.now()
|
||||
instance.static_users.add(*users_to_add)
|
||||
instance.excluded_users.add(*users_to_exclude)
|
||||
|
||||
|
Reference in New Issue
Block a user