Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

refactor(tags): stop writing the legacy tagged item keys (#103937)

Yasenb3174043f538
diff --git a/.semgrep/rules/security/max-tools-require-serializer.py b/.semgrep/rules/security/max-tools-require-serializer.py
index 4f68edf0c0e6..2191c93102d0 100644
--- a/.semgrep/rules/security/max-tools-require-serializer.py
+++ b/.semgrep/rules/security/max-tools-require-serializer.py
@@ -57,7 +57,7 @@ def safe_different_model(team_id):
def safe_tagged_item(tag, flag):
# TaggedItem not in list - no dedicated serializer
# ok: max-tools-direct-model-create
- TaggedItem.objects.create(tag=tag, feature_flag=flag)
+ flag.tagged_items.create(tag=tag)
def safe_experiment_not_in_list(team):
diff --git a/posthog/api/test/dashboards/__snapshots__/test_dashboard.ambr b/posthog/api/test/dashboards/__snapshots__/test_dashboard.ambr
index f186fe88fd66..f488d7440546 100644
--- a/posthog/api/test/dashboards/__snapshots__/test_dashboard.ambr
+++ b/posthog/api/test/dashboards/__snapshots__/test_dashboard.ambr
@@ -1749,19 +1749,6 @@
'''
SELECT "posthog_taggeditem"."id",
"posthog_taggeditem"."tag_id",
- "posthog_taggeditem"."dashboard_id",
- "posthog_taggeditem"."insight_id",
- "posthog_taggeditem"."event_definition_id",
- "posthog_taggeditem"."property_definition_id",
- "posthog_taggeditem"."action_id",
- "posthog_taggeditem"."feature_flag_id",
- "posthog_taggeditem"."experiment_saved_metric_id",
- "posthog_taggeditem"."ticket_id",
- "posthog_taggeditem"."account_id",
- "posthog_taggeditem"."endpoint_id",
- "posthog_taggeditem"."replay_scanner_id",
- "posthog_taggeditem"."project_id",
- "posthog_taggeditem"."experiment_id",
"posthog_taggeditem"."content_type_id",
"posthog_taggeditem"."object_id",
"posthog_taggeditem"."object_uuid",
@@ -2442,19 +2429,6 @@
'''
SELECT "posthog_taggeditem"."id",
"posthog_taggeditem"."tag_id",
- "posthog_taggeditem"."dashboard_id",
- "posthog_taggeditem"."insight_id",
- "posthog_taggeditem"."event_definition_id",
- "posthog_taggeditem"."property_definition_id",
- "posthog_taggeditem"."action_id",
- "posthog_taggeditem"."feature_flag_id",
- "posthog_taggeditem"."experiment_saved_metric_id",
- "posthog_taggeditem"."ticket_id",
- "posthog_taggeditem"."account_id",
- "posthog_taggeditem"."endpoint_id",
- "posthog_taggeditem"."replay_scanner_id",
- "posthog_taggeditem"."project_id",
- "posthog_taggeditem"."experiment_id",
"posthog_taggeditem"."content_type_id",
"posthog_taggeditem"."object_id",
"posthog_taggeditem"."object_uuid",
@@ -4064,19 +4038,6 @@
'''
SELECT "posthog_taggeditem"."id",
"posthog_taggeditem"."tag_id",
- "posthog_taggeditem"."dashboard_id",
- "posthog_taggeditem"."insight_id",
- "posthog_taggeditem"."event_definition_id",
- "posthog_taggeditem"."property_definition_id",
- "posthog_taggeditem"."action_id",
- "posthog_taggeditem"."feature_flag_id",
- "posthog_taggeditem"."experiment_saved_metric_id",
- "posthog_taggeditem"."ticket_id",
- "posthog_taggeditem"."account_id",
- "posthog_taggeditem"."endpoint_id",
- "posthog_taggeditem"."replay_scanner_id",
- "posthog_taggeditem"."project_id",
- "posthog_taggeditem"."experiment_id",
"posthog_taggeditem"."content_type_id",
"posthog_taggeditem"."object_id",
"posthog_taggeditem"."object_uuid",
@@ -7440,19 +7401,6 @@
'''
SELECT "posthog_taggeditem"."id",
"posthog_taggeditem"."tag_id",
- "posthog_taggeditem"."dashboard_id",
- "posthog_taggeditem"."insight_id",
- "posthog_taggeditem"."event_definition_id",
- "posthog_taggeditem"."property_definition_id",
- "posthog_taggeditem"."action_id",
- "posthog_taggeditem"."feature_flag_id",
- "posthog_taggeditem"."experiment_saved_metric_id",
- "posthog_taggeditem"."ticket_id",
- "posthog_taggeditem"."account_id",
- "posthog_taggeditem"."endpoint_id",
- "posthog_taggeditem"."replay_scanner_id",
- "posthog_taggeditem"."project_id",
- "posthog_taggeditem"."experiment_id",
"posthog_taggeditem"."content_type_id",
"posthog_taggeditem"."object_id",
"posthog_taggeditem"."object_uuid",
@@ -8129,19 +8077,6 @@
'''
SELECT "posthog_taggeditem"."id",
"posthog_taggeditem"."tag_id",
- "posthog_taggeditem"."dashboard_id",
- "posthog_taggeditem"."insight_id",
- "posthog_taggeditem"."event_definition_id",
- "posthog_taggeditem"."property_definition_id",
- "posthog_taggeditem"."action_id",
- "posthog_taggeditem"."feature_flag_id",
- "posthog_taggeditem"."experiment_saved_metric_id",
- "posthog_taggeditem"."ticket_id",
- "posthog_taggeditem"."account_id",
- "posthog_taggeditem"."endpoint_id",
- "posthog_taggeditem"."replay_scanner_id",
- "posthog_taggeditem"."project_id",
- "posthog_taggeditem"."experiment_id",
"posthog_taggeditem"."content_type_id",
"posthog_taggeditem"."object_id",
"posthog_taggeditem"."object_uuid",
@@ -12923,19 +12858,6 @@
'''
SELECT "posthog_taggeditem"."id",
"posthog_taggeditem"."tag_id",
- "posthog_taggeditem"."dashboard_id",
- "posthog_taggeditem"."insight_id",
- "posthog_taggeditem"."event_definition_id",
- "posthog_taggeditem"."property_definition_id",
- "posthog_taggeditem"."action_id",
- "posthog_taggeditem"."feature_flag_id",
- "posthog_taggeditem"."experiment_saved_metric_id",
- "posthog_taggeditem"."ticket_id",
- "posthog_taggeditem"."account_id",
- "posthog_taggeditem"."endpoint_id",
- "posthog_taggeditem"."replay_scanner_id",
- "posthog_taggeditem"."project_id",
- "posthog_taggeditem"."experiment_id",
"posthog_taggeditem"."content_type_id",
"posthog_taggeditem"."object_id",
"posthog_taggeditem"."object_uuid",
@@ -16379,19 +16301,6 @@
'''
SELECT "posthog_taggeditem"."id",
"posthog_taggeditem"."tag_id",
- "posthog_taggeditem"."dashboard_id",
- "posthog_taggeditem"."insight_id",
- "posthog_taggeditem"."event_definition_id",
- "posthog_taggeditem"."property_definition_id",
- "posthog_taggeditem"."action_id",
- "posthog_taggeditem"."feature_flag_id",
- "posthog_taggeditem"."experiment_saved_metric_id",
- "posthog_taggeditem"."ticket_id",
- "posthog_taggeditem"."account_id",
- "posthog_taggeditem"."endpoint_id",
- "posthog_taggeditem"."replay_scanner_id",
- "posthog_taggeditem"."project_id",
- "posthog_taggeditem"."experiment_id",
"posthog_taggeditem"."content_type_id",
"posthog_taggeditem"."object_id",
"posthog_taggeditem"."object_uuid",
diff --git a/posthog/migrations/1376_taggeditem_untrack_legacy_keys.py b/posthog/migrations/1376_taggeditem_untrack_legacy_keys.py
new file mode 100644
index 000000000000..5ade108b8af0
--- /dev/null
+++ b/posthog/migrations/1376_taggeditem_untrack_legacy_keys.py
@@ -0,0 +1,45 @@
+from django.db import migrations
+
+from posthog.migration_helpers import DropForeignKey, untrack_field
+
+# The per-model foreign keys TaggedItem carried before the generic pointer replaced them.
+LEGACY_FIELDS = (
+ "dashboard",
+ "insight",
+ "event_definition",
+ "property_definition",
+ "action",
+ "feature_flag",
+ "experiment_saved_metric",
+ "ticket",
+ "account",
+ "endpoint",
+ "replay_scanner",
+ "project",
+ "experiment",
+)
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("posthog", "1375_file_system_home_folder"),
+ ]
+
+ operations = [
+ # The constraints go first. A row written by the next release sets no legacy key, so
+ # the check would reject every insert while the two releases run side by side.
+ migrations.AlterUniqueTogether(name="taggeditem", unique_together=set()),
+ *[
+ migrations.RemoveConstraint(model_name="taggeditem", name=f"unique_{field}_tagged_item")
+ for field in LEGACY_FIELDS
+ ],
+ migrations.RemoveConstraint(model_name="taggeditem", name="exactly_one_related_object"),
+ # The columns stay, so a pod on the old release keeps reading and writing them. Their
+ # foreign keys cannot: Django stops cascading into a relation it no longer tracks, and
+ # a deferred constraint would then fail every parent delete at COMMIT.
+ untrack_field(
+ "taggeditem",
+ *LEGACY_FIELDS,
+ database_operations=[DropForeignKey("posthog_taggeditem", column=f"{field}_id") for field in LEGACY_FIELDS],
+ ),
+ ]
diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txt
index d5d2d8b3bfd3..2ce48f57d3a1 100644
--- a/posthog/migrations/max_migration.txt
+++ b/posthog/migrations/max_migration.txt
@@ -1 +1 @@
-1375_file_system_home_folder
+1376_taggeditem_untrack_legacy_keys
diff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.py
index d39eee6f3c34..6b55d1723da4 100644
--- a/posthog/models/activity_logging/activity_log.py
+++ b/posthog/models/activity_logging/activity_log.py
@@ -586,7 +586,8 @@ field_exclusions: dict[AuditableScope, list[str]] = {
"ReplayScanner": [*replay_scanner_machine_fields, "observations", "backfills", "prompt_suggestions", "alerts"],
"VisionAlertConfiguration": [*vision_alert_machine_fields, "events", "matches"],
"DataQualityCheckSchedule": ["subject_type", "subject_uuid", "next_run_at", "last_run_at", "last_suite_run"],
- # The generic pointer mirrors whichever per-model foreign key is set, so it is never a user edit.
+ # The pointer names the tagged object, which a row never changes, and content_type and team
+ # are model objects the diff cannot serialize.
"TaggedItem": ["content_type", "object_id", "object_uuid", "team"],
"StamphogRepoConfig": [
# Reverse relation to the repo's review history. The diff would read every pull request row
diff --git a/posthog/models/tagged_item.py b/posthog/models/tagged_item.py
index f5c5d764ff85..692732b96cf5 100644
--- a/posthog/models/tagged_item.py
+++ b/posthog/models/tagged_item.py
@@ -16,28 +16,11 @@ from posthog.models.tagged_item_registry import (
object_column_for,
require_taggable,
taggable_for_content_type_id,
- taggable_for_legacy_field,
)
-from posthog.models.utils import UUIDTModel, build_partial_uniqueness_constraint, build_unique_relationship_check
+from posthog.models.utils import UUIDTModel
GENERIC_POINTER_FIELDS = ("content_type", "object_id", "object_uuid", "team")
-RELATED_OBJECTS = (
- "dashboard",
- "insight",
- "event_definition",
- "property_definition",
- "action",
- "feature_flag",
- "experiment_saved_metric",
- "ticket",
- "account",
- "endpoint",
- "replay_scanner",
- "project",
- "experiment",
-)
-
class TaggedItemQuerySet(models.QuerySet):
"""Ways of selecting tagged items by what they tag, without naming a column."""
@@ -68,7 +51,7 @@ class TaggedItemQuerySet(models.QuerySet):
for obj in objs:
if obj.tag_id in tags:
obj.tag = tags[obj.tag_id]
- obj.sync_foreign_keys()
+ obj.sync_team()
return super().bulk_create(objs, *args, **kwargs)
@@ -83,113 +66,12 @@ class TaggedItem(ModelActivityMixin, UUIDTModel):
We want to deprecate model-specific tags and refactor tag relationships into a separate table that keeps track of
tag-object relationships.
- Models that are taggable throughout the app are listed as separate fields below.
+ Models that are taggable throughout the app are listed in `TAGGABLE_MODELS`.
https://docs.djangoproject.com/en/4.0/ref/contrib/contenttypes/#generic-relations
"""
tag = models.ForeignKey("Tag", on_delete=models.CASCADE, related_name="tagged_items")
- # When adding a new taggeditem-model relationship, make sure to add the foreign key field and append field name to
- # the `RELATED_OBJECTS` tuple above.
- dashboard = models.ForeignKey(
- "dashboards.Dashboard",
- on_delete=models.CASCADE,
- null=True,
- blank=True,
- related_name="+",
- )
- insight = models.ForeignKey(
- "product_analytics.Insight",
- on_delete=models.CASCADE,
- null=True,
- blank=True,
- related_name="+",
- )
- event_definition = models.ForeignKey(
- "event_definitions.EventDefinition",
- on_delete=models.CASCADE,
- null=True,
- blank=True,
- related_name="+",
- )
- property_definition = models.ForeignKey(
- "event_definitions.PropertyDefinition",
- on_delete=models.CASCADE,
- null=True,
- blank=True,
- related_name="+",
- )
- action = models.ForeignKey(
- "actions.Action",
- on_delete=models.CASCADE,
- null=True,
- blank=True,
- related_name="+",
- )
- feature_flag = models.ForeignKey(
- "feature_flags.FeatureFlag",
- on_delete=models.CASCADE,
- null=True,
- blank=True,
- related_name="+",
- )
- experiment_saved_metric = models.ForeignKey(
- "experiments.ExperimentSavedMetric",
- on_delete=models.CASCADE,
- null=True,
- blank=True,
- related_name="+",
- )
- ticket = models.ForeignKey(
- "conversations.Ticket",
- on_delete=models.CASCADE,
- null=True,
- blank=True,
- related_name="+",
- )
- account = models.ForeignKey(
- "customer_analytics.Account",
- on_delete=models.CASCADE,
- null=True,
- blank=True,
- related_name="+",
- )
- endpoint = models.ForeignKey(
- "endpoints.Endpoint",
- on_delete=models.CASCADE,
- null=True,
- blank=True,
- related_name="+",
- )
- replay_scanner = models.ForeignKey(
- "replay_vision.ReplayScanner",
- on_delete=models.CASCADE,
- null=True,
- blank=True,
- related_name="+",
- )
- project = models.ForeignKey(
- "posthog.Project",
- on_delete=models.CASCADE,
- null=True,
- blank=True,
- related_name="+",
- # posthog_project is read on nearly every request, so creating this FK's database
- # constraint inline would lock it. A later migration adds the constraint NOT VALID
- # and validates it separately.
- db_constraint=False,
- )
- experiment = models.ForeignKey(
- "experiments.Experiment",
- on_delete=models.CASCADE,
- null=True,
- blank=True,
- related_name="+",
- # Same deferred-FK pattern as project: the constraint lands NOT VALID in a later
- # migration and is validated separately, keeping the lock on posthog_experiment brief.
- db_constraint=False,
- )
-
# db_index=False on both keys below: Django would build that index non-concurrently
# inside the AddField transaction, locking the table.
content_type = models.ForeignKey(
@@ -218,7 +100,6 @@ class TaggedItem(ModelActivityMixin, UUIDTModel):
uuid_object = GenericForeignKey("content_type", "object_uuid")
class Meta:
- unique_together = ("tag", *RELATED_OBJECTS)
indexes = [
# Most integer-keyed models declare BigAutoField, so Django casts object_id to bigint
# when it joins to them, and the unique index on the raw column cannot serve that join.
@@ -229,17 +110,7 @@ class TaggedItem(ModelActivityMixin, UUIDTModel):
name="taggeditem_object_id_bigint",
),
]
- # Make sure to add new key to uniqueness constraint when extending tag functionality to new model
constraints = [
- *[
- build_partial_uniqueness_constraint(
- field="tag", related_field=related_field, constraint_name=f"unique_{related_field}_tagged_item"
- )
- for related_field in RELATED_OBJECTS
- ],
- models.CheckConstraint(
- condition=build_unique_relationship_check(RELATED_OBJECTS), name="exactly_one_related_object"
- ),
models.CheckConstraint(
condition=Q(content_type__isnull=False, team__isnull=False)
& (
@@ -261,10 +132,17 @@ class TaggedItem(ModelActivityMixin, UUIDTModel):
]
def clean(self):
+ """Ensure the row names exactly one taggable object, through the column its model uses."""
super().clean()
- """Ensure that exactly one of object columns can be set."""
- if sum(map(bool, [getattr(self, o_field) for o_field in RELATED_OBJECTS])) != 1:
- raise ValidationError("Exactly one object field must be set.")
+ if self.content_type_id is None:
+ raise ValidationError("A tagged item must have a content type.")
+ if (self.object_id is None) == (self.object_uuid is None):
+ raise ValidationError("Exactly one object column must be set.")
+ entry = self._taggable_entry
+ if entry is None:
+ raise ValidationError("The content type is not a taggable model.")
+ if getattr(self, entry.object_field) is None:
+ raise ValidationError(f"A tag on {self.content_type} belongs on {entry.object_field}.")
objects = TaggedItemQuerySet.as_manager()
@@ -299,51 +177,15 @@ class TaggedItem(ModelActivityMixin, UUIDTModel):
return self.uuid_object
return None
- def sync_legacy_foreign_key(self) -> None:
- """Point the per-model foreign key at the object the generic pointer names."""
- entry = self._taggable_entry
- # A row built with a content type and only a legacy key keeps that key.
- if entry is None or getattr(self, entry.object_field) is None:
- return
- for legacy_field in RELATED_OBJECTS:
- setattr(self, f"{legacy_field}_id", None)
- setattr(self, f"{entry.legacy_field}_id", getattr(self, entry.object_field))
-
- def sync_foreign_keys(self) -> None:
- """Make the two pointer shapes agree, preferring the generic one when it is set."""
- if self.content_type_id is not None:
- self.sync_legacy_foreign_key()
- self.sync_generic_columns()
-
- def sync_generic_columns(self) -> None:
- """Fill the generic pointer from whichever per-model foreign key is set.
-
- Reads `<field>_id` rather than `<field>`, so it resolves the target without loading it.
- """
- self.content_type = None
- self.object_id = None
- self.object_uuid = None
- for legacy_field in RELATED_OBJECTS:
- related_id = getattr(self, f"{legacy_field}_id", None)
- if related_id is None:
- continue
-
- entry = taggable_for_legacy_field(legacy_field)
- if entry is None:
- continue
-
- self.content_type = content_type_for_entry(entry)
- setattr(self, entry.object_field, related_id)
- self.team_id = self.tag.team_id
- return
+ def sync_team(self) -> None:
+ """Take the team from the tag, which is the row's owner."""
+ self.team_id = self.tag.team_id
def save(self, *args, **kwargs):
- if self.content_type_id is not None:
- self.sync_legacy_foreign_key()
- self.full_clean(exclude=GENERIC_POINTER_FIELDS)
- self.sync_generic_columns()
+ self.sync_team()
+ self.full_clean()
if kwargs.get("update_fields"):
- kwargs["update_fields"] = {*kwargs["update_fields"], *GENERIC_POINTER_FIELDS, *RELATED_OBJECTS}
+ kwargs["update_fields"] = {*kwargs["update_fields"], *GENERIC_POINTER_FIELDS}
return super().save(*args, **kwargs)
def __str__(self) -> str:
diff --git a/posthog/models/test/test_tagged_item_model.py b/posthog/models/test/test_tagged_item_model.py
index ddf642ad827c..8e271a1c4ff2 100644
--- a/posthog/models/test/test_tagged_item_model.py
+++ b/posthog/models/test/test_tagged_item_model.py
@@ -7,25 +7,36 @@ from django.db import models
from parameterized import parameterized
from posthog.models import Tag, TaggedItem, Team
+from posthog.models.tagged_items_relation import Taggable
from products.actions.backend.models.action import Action
from products.dashboards.backend.models.dashboard import Dashboard
-from products.dashboards.backend.models.dashboard_tile import DashboardTile
from products.event_definitions.backend.models import EventDefinition
from products.product_analytics.backend.facade.models import Insight
class TestTaggedItem(BaseTest):
+ def _taggable(self, kind: str) -> Taggable:
+ if kind == "dashboard":
+ return Dashboard.objects.create(team_id=self.team.id, name="dashboard")
+ if kind == "insight":
+ return Insight.objects.create(filters={"events": [{"id": "$pageview"}]}, team_id=self.team.id)
+ if kind == "event_definition":
+ return EventDefinition.objects.create(team=self.team, name="event")
+ return Action.objects.create(team=self.team, name="action")
+
def test_exactly_one_object_constraint(self):
- # Setup
dashboard = Dashboard.objects.create(team_id=self.team.id, name="private dashboard")
- insight = Insight.objects.create(filters={"events": [{"id": "$pageview"}]}, team_id=self.team.id)
- DashboardTile.objects.create(insight=insight, dashboard=dashboard)
+ event_definition = EventDefinition.objects.create(team=self.team, name="event")
tag = Tag.objects.create(name="tag", team_id=self.team.id)
- # Before migration you can create duplicate tagged items
with self.assertRaises(ValidationError):
- TaggedItem.objects.create(dashboard_id=dashboard.id, insight_id=insight.id, tag_id=tag.id)
+ TaggedItem.objects.create(
+ tag_id=tag.id,
+ content_type=ContentType.objects.get_for_model(Dashboard),
+ object_id=dashboard.id,
+ object_uuid=event_definition.id,
+ )
def test_at_least_one_constraint(self):
tag = Tag.objects.create(name="tag", team_id=self.team.id)
@@ -33,75 +44,65 @@ class TestTaggedItem(BaseTest):
with self.assertRaises(ValidationError):
TaggedItem.objects.create(tag_id=tag.id)
- def test_uniqueness_constraint_dashboard(self):
+ def test_content_type_is_required(self):
dashboard = Dashboard.objects.create(team_id=self.team.id, name="private dashboard")
tag = Tag.objects.create(name="tag", team_id=self.team.id)
- TaggedItem.objects.create(dashboard_id=dashboard.id, tag_id=tag.id)
with self.assertRaises(ValidationError):
- TaggedItem.objects.create(dashboard_id=dashboard.id, tag_id=tag.id)
+ TaggedItem.objects.create(tag_id=tag.id, object_id=dashboard.id)
- def test_uniqueness_constraint_insight(self):
- dashboard = Dashboard.objects.create(team_id=self.team.id, name="private dashboard")
- insight = Insight.objects.create(filters={"events": [{"id": "$pageview"}]}, team_id=self.team.id)
- DashboardTile.objects.create(insight=insight, dashboard=dashboard)
+ def test_unregistered_content_type_is_rejected(self):
tag = Tag.objects.create(name="tag", team_id=self.team.id)
- TaggedItem.objects.create(insight_id=insight.id, tag_id=tag.id)
with self.assertRaises(ValidationError):
- TaggedItem.objects.create(insight_id=insight.id, tag_id=tag.id)
+ TaggedItem.objects.create(
+ tag_id=tag.id, content_type=ContentType.objects.get_for_model(Team), object_id=self.team.id
+ )
- def test_uniqueness_constraint_event_definition(self):
- try:
- from ee.models import EnterpriseEventDefinition
- except ImportError:
- pass
- else:
- event_definition = EnterpriseEventDefinition.objects.create(
- team=self.team, name="enterprise event", owner=self.user
+ def test_object_column_must_match_the_content_type(self):
+ """A row filed under the wrong typed column reads back as no object at all."""
+ event_definition = EventDefinition.objects.create(team=self.team, name="event")
+ tag = Tag.objects.create(name="tag", team_id=self.team.id)
+
+ with self.assertRaises(ValidationError):
+ TaggedItem.objects.create(
+ tag_id=tag.id,
+ content_type=ContentType.objects.get_for_model(EventDefinition),
+ object_id=self.team.id,
)
- tag = Tag.objects.create(name="tag", team_id=self.team.id)
+ assert event_definition.tagged_items.count() == 0
- TaggedItem.objects.create(event_definition_id=event_definition.id, tag_id=tag.id)
- with self.assertRaises(ValidationError):
- TaggedItem.objects.create(event_definition_id=event_definition.id, tag_id=tag.id)
+ @parameterized.expand(["dashboard", "insight", "event_definition", "action"])
+ def test_uniqueness_constraint(self, kind: str):
+ tag = Tag.objects.create(name="tag", team_id=self.team.id)
+ obj = self._taggable(kind)
+
+ obj.tagged_items.create(tag=tag)
+ with self.assertRaises(ValidationError):
+ obj.tagged_items.create(tag=tag)
def test_uniqueness_constraint_property_definition(self):
try:
from ee.models import EnterprisePropertyDefinition
except ImportError:
- pass
- else:
- property_definition = EnterprisePropertyDefinition.objects.create(
- team=self.team, name="enterprise property"
- )
- tag = Tag.objects.create(name="tag", team_id=self.team.id)
-
- TaggedItem.objects.create(property_definition_id=property_definition.id, tag_id=tag.id)
- with self.assertRaises(ValidationError):
- TaggedItem.objects.create(property_definition_id=property_definition.id, tag_id=tag.id)
+ self.skipTest("needs the ee app")
- def test_uniqueness_constraint_action(self):
- action = Action.objects.create(team=self.team, name="enterprise property")
+ property_definition = EnterprisePropertyDefinition.objects.create(team=self.team, name="enterprise property")
tag = Tag.objects.create(name="tag", team_id=self.team.id)
- TaggedItem.objects.create(action_id=action.id, tag_id=tag.id)
+ property_definition.tagged_items.create(tag=tag)
with self.assertRaises(ValidationError):
- TaggedItem.objects.create(action_id=action.id, tag_id=tag.id)
+ property_definition.tagged_items.create(tag=tag)
class TestTaggedItemGenericColumns(BaseTest):
- """The generic pointer is filled from whichever per-model foreign key is set.
-
- Both shapes are written until the migration finishes, so these assert the new columns
- agree with the old ones rather than replace them.
- """
+ """The pointer columns name the tagged object, and the team follows the tag."""
def test_integer_keyed_object_fills_object_id(self):
dashboard = Dashboard.objects.create(team_id=self.team.id, name="dashboard")
tag = Tag.objects.create(name="tag", team_id=self.team.id)
- tagged_item = TaggedItem.objects.create(dashboard_id=dashboard.id, tag_id=tag.id)
+ tagged_item = dashboard.tagged_items.create(tag=tag)
tagged_item.refresh_from_db()
assert tagged_item.object_id == dashboard.id
@@ -113,7 +114,7 @@ class TestTaggedItemGenericColumns(BaseTest):
event_definition = EventDefinition.objects.create(team=self.team, name="event")
tag = Tag.objects.create(name="tag", team_id=self.team.id)
- tagged_item = TaggedItem.objects.create(event_definition_id=event_definition.id, tag_id=tag.id)
+ tagged_item = event_definition.tagged_items.create(tag=tag)
tagged_item.refresh_from_db()
assert tagged_item.object_uuid == event_definition.id
@@ -131,21 +132,24 @@ class TestTaggedItemGenericColumns(BaseTest):
event_definition = EnterpriseEventDefinition.objects.create(team=self.team, name="enterprise event")
tag = Tag.objects.create(name="tag", team_id=self.team.id)
- tagged_item = TaggedItem.objects.create(event_definition_id=event_definition.id, tag_id=tag.id)
+ tagged_item = event_definition.tagged_items.create(tag=tag)
tagged_item.refresh_from_db()
assert tagged_item.content_type == ContentType.objects.get_for_model(EventDefinition)
assert tagged_item.content_type != ContentType.objects.get_for_model(EnterpriseEventDefinition)
assert tagged_item.object_uuid == event_definition.id
- def test_bulk_create_fills_the_generic_columns(self):
+ def test_bulk_create_fills_the_team(self):
"""bulk_create never calls save(), and the Zendesk import writes ticket tags through it."""
dashboard = Dashboard.objects.create(team_id=self.team.id, name="dashboard")
event_definition = EventDefinition.objects.create(team=self.team, name="event")
tag = Tag.objects.create(name="tag", team_id=self.team.id)
TaggedItem.objects.bulk_create(
- [TaggedItem(tag=tag, dashboard=dashboard), TaggedItem(tag=tag, event_definition=event_definition)]
+ [
+ TaggedItem.for_content_object(tag, dashboard),
+ TaggedItem.for_content_object(tag, event_definition),
+ ]
)
by_type = {item.related_object_type: item for item in TaggedItem.objects.filter(tag=tag)}
@@ -158,33 +162,21 @@ class TestTaggedItemGenericColumns(BaseTest):
def test_bulk_create_loads_uncached_tags_once(self):
dashboards = [Dashboard.objects.create(team_id=self.team.id, name=f"dashboard {i}") for i in range(3)]
tag = Tag.objects.create(name="tag", team_id=self.team.id)
- rows = [TaggedItem(tag_id=tag.id, dashboard=dashboard) for dashboard in dashboards]
- ContentType.objects.get_for_model(Dashboard)
+ content_type = ContentType.objects.get_for_model(Dashboard)
+ rows = [
+ TaggedItem(tag_id=tag.id, content_type=content_type, object_id=dashboard.id) for dashboard in dashboards
+ ]
with self.assertNumQueries(2):
TaggedItem.objects.bulk_create(rows)
assert all(row.team_id == tag.team_id for row in rows)
- def test_retargeting_a_row_clears_the_other_object_column(self):
- dashboard = Dashboard.objects.create(team_id=self.team.id, name="dashboard")
- event_definition = EventDefinition.objects.create(team=self.team, name="event")
- tag = Tag.objects.create(name="tag", team_id=self.team.id)
- tagged_item = TaggedItem.objects.create(dashboard_id=dashboard.id, tag_id=tag.id)
-
- tagged_item.dashboard = None
- tagged_item.event_definition = event_definition
- tagged_item.sync_generic_columns()
-
- assert tagged_item.object_id is None
- assert tagged_item.object_uuid == event_definition.id
- assert tagged_item.content_type == ContentType.objects.get_for_model(EventDefinition)
-
- def test_save_with_update_fields_persists_the_generic_columns(self):
+ def test_save_with_update_fields_persists_the_team(self):
dashboard = Dashboard.objects.create(team_id=self.team.id, name="dashboard")
tag = Tag.objects.create(name="tag", team_id=self.team.id)
other_team = Team.objects.create(organization=self.organization, name="other")
- tagged_item = TaggedItem.objects.create(dashboard_id=dashboard.id, tag_id=tag.id)
+ tagged_item = dashboard.tagged_items.create(tag=tag)
TaggedItem.objects.filter(pk=tagged_item.pk).update(team_id=other_team.id)
tagged_item = TaggedItem.objects.get(pk=tagged_item.pk)
@@ -196,12 +188,10 @@ class TestTaggedItemGenericColumns(BaseTest):
def test_team_follows_the_tag(self):
dashboard = Dashboard.objects.create(team_id=self.team.id, name="dashboard")
other_team = Team.objects.create(organization=self.organization, name="other")
- tagged_item = TaggedItem.objects.create(
- dashboard_id=dashboard.id, tag=Tag.objects.create(name="tag", team_id=self.team.id)
- )
+ tagged_item = dashboard.tagged_items.create(tag=Tag.objects.create(name="tag", team_id=self.team.id))
tagged_item.tag = Tag.objects.create(name="tag", team_id=other_team.id)
- tagged_item.sync_generic_columns()
+ tagged_item.sync_team()
assert tagged_item.team_id == other_team.id
@@ -209,7 +199,7 @@ class TestTaggedItemGenericColumns(BaseTest):
insight = Insight.objects.create(filters={"events": [{"id": "$pageview"}]}, team_id=self.team.id)
tag = Tag.objects.create(name="tag", team_id=self.team.id)
- tagged_item = TaggedItem.objects.create(insight_id=insight.id, tag_id=tag.id)
+ tagged_item = insight.tagged_items.create(tag=tag)
assert tagged_item.related_object_type == "insight"
assert tagged_item.content_object == insight
@@ -218,8 +208,8 @@ class TestTaggedItemGenericColumns(BaseTest):
dashboard = Dashboard.objects.create(team_id=self.team.id, name="dashboard")
other_dashboard = Dashboard.objects.create(team_id=self.team.id, name="other dashboard")
tag = Tag.objects.create(name="tag", team_id=self.team.id)
- tagged_item = TaggedItem.objects.create(dashboard_id=dashboard.id, tag_id=tag.id)
- TaggedItem.objects.create(dashboard_id=other_dashboard.id, tag_id=tag.id)
+ tagged_item = dashboard.tagged_items.create(tag=tag)
+ other_dashboard.tagged_items.create(tag=tag)
assert list(TaggedItem.objects.for_object(dashboard)) == [tagged_item]
assert TaggedItem.objects.for_model(Dashboard).count() == 2
@@ -227,15 +217,15 @@ class TestTaggedItemGenericColumns(BaseTest):
class TestTaggedItemsRelation(BaseTest):
- def test_reverse_accessor_writes_both_pointer_shapes(self):
+ def test_reverse_accessor_writes_the_pointer(self):
dashboard = Dashboard.objects.create(team_id=self.team.id, name="dashboard")
tag = Tag.objects.create(name="tag", team_id=self.team.id)
tagged_item, _ = dashboard.tagged_items.get_or_create(tag=tag)
tagged_item.refresh_from_db()
- assert tagged_item.dashboard_id == dashboard.id
assert tagged_item.object_id == dashboard.id
+ assert tagged_item.content_type == ContentType.objects.get_for_model(Dashboard)
assert tagged_item.team_id == tag.team_id
assert list(dashboard.tagged_items.all()) == [tagged_item]
@@ -252,25 +242,7 @@ class TestTaggedItemsRelation(BaseTest):
target.tagged_items.set([item])
item.refresh_from_db()
- assert (item.object_id, item.dashboard_id) == (source.id, source.id)
-
- def test_reads_ignore_the_legacy_key(self):
- followed = Dashboard.objects.create(team_id=self.team.id, name="followed")
- ignored = Dashboard.objects.create(team_id=self.team.id, name="ignored")
- tag = Tag.objects.create(name="tag", team_id=self.team.id)
- item = TaggedItem.objects.create(dashboard_id=followed.id, tag=tag)
- TaggedItem.objects.filter(pk=item.pk).update(dashboard_id=ignored.id)
- item.refresh_from_db()
- both = [followed.pk, ignored.pk]
-
- assert list(followed.tagged_items.all()) == [item]
- assert list(ignored.tagged_items.all()) == []
- assert list(Dashboard.objects.filter(tagged_items__tag=tag)) == [followed]
- assert list(Dashboard.objects.filter(pk__in=both).exclude(tagged_items__tag=tag)) == [ignored]
- prefetched = Dashboard.objects.filter(pk__in=both).prefetch_related("tagged_items")
- assert {d.pk: list(d.tagged_items.all()) for d in prefetched} == {followed.pk: [item], ignored.pk: []}
- assert list(TaggedItem.objects.for_object(followed)) == [item]
- assert item.content_object == followed
+ assert item.object_id == source.id
@parameterized.expand([("integer key", "dashboard"), ("uuid key", "event_definition")])
def test_filter_and_prefetch_through_the_relation(self, _name: str, kind: str):
@@ -324,13 +296,13 @@ class TestTaggedItemsRelation(BaseTest):
assert not TaggedItem.objects.for_model(Dashboard).exists()
- def test_bulk_create_from_content_objects_fills_the_legacy_key(self):
+ def test_bulk_create_from_content_objects_fills_the_pointer(self):
dashboard = Dashboard.objects.create(team_id=self.team.id, name="dashboard")
tag = Tag.objects.create(name="tag", team_id=self.team.id)
TaggedItem.objects.bulk_create([TaggedItem.for_content_object(tag, dashboard)])
tagged_item = TaggedItem.objects.for_object(dashboard).get()
- assert tagged_item.dashboard_id == dashboard.id
+ assert tagged_item.object_id == dashboard.id
assert tagged_item.related_object_type == "dashboard"
assert tagged_item.content_object == dashboard
diff --git a/posthog/tasks/test/__snapshots__/test_process_scheduled_changes.ambr b/posthog/tasks/test/__snapshots__/test_process_scheduled_changes.ambr
index f1e0f8f3961d..d894e3e14f7a 100644
--- a/posthog/tasks/test/__snapshots__/test_process_scheduled_changes.ambr
+++ b/posthog/tasks/test/__snapshots__/test_process_scheduled_changes.ambr
@@ -320,19 +320,6 @@
'''
SELECT "posthog_taggeditem"."id",
"posthog_taggeditem"."tag_id",
- "posthog_taggeditem"."dashboard_id",
- "posthog_taggeditem"."insight_id",
- "posthog_taggeditem"."event_definition_id",
- "posthog_taggeditem"."property_definition_id",
- "posthog_taggeditem"."action_id",
- "posthog_taggeditem"."feature_flag_id",
- "posthog_taggeditem"."experiment_saved_metric_id",
- "posthog_taggeditem"."ticket_id",
- "posthog_taggeditem"."account_id",
- "posthog_taggeditem"."endpoint_id",
- "posthog_taggeditem"."replay_scanner_id",
- "posthog_taggeditem"."project_id",
- "posthog_taggeditem"."experiment_id",
"posthog_taggeditem"."content_type_id",
"posthog_taggeditem"."object_id",
"posthog_taggeditem"."object_uuid",
@@ -346,19 +333,6 @@
'''
SELECT "posthog_taggeditem"."id",
"posthog_taggeditem"."tag_id",
- "posthog_taggeditem"."dashboard_id",
- "posthog_taggeditem"."insight_id",
- "posthog_taggeditem"."event_definition_id",
- "posthog_taggeditem"."property_definition_id",
- "posthog_taggeditem"."action_id",
- "posthog_taggeditem"."feature_flag_id",
- "posthog_taggeditem"."experiment_saved_metric_id",
- "posthog_taggeditem"."ticket_id",
- "posthog_taggeditem"."account_id",
- "posthog_taggeditem"."endpoint_id",
- "posthog_taggeditem"."replay_scanner_id",
- "posthog_taggeditem"."project_id",
- "posthog_taggeditem"."experiment_id",
"posthog_taggeditem"."content_type_id",
"posthog_taggeditem"."object_id",
"posthog_taggeditem"."object_uuid",
@@ -1301,19 +1275,6 @@
'''
SELECT "posthog_taggeditem"."id",
"posthog_taggeditem"."tag_id",
- "posthog_taggeditem"."dashboard_id",
- "posthog_taggeditem"."insight_id",
- "posthog_taggeditem"."event_definition_id",
- "posthog_taggeditem"."property_definition_id",
- "posthog_taggeditem"."action_id",
- "posthog_taggeditem"."feature_flag_id",
- "posthog_taggeditem"."experiment_saved_metric_id",
- "posthog_taggeditem"."ticket_id",
- "posthog_taggeditem"."account_id",
- "posthog_taggeditem"."endpoint_id",
- "posthog_taggeditem"."replay_scanner_id",
- "posthog_taggeditem"."project_id",
- "posthog_taggeditem"."experiment_id",
"posthog_taggeditem"."content_type_id",
"posthog_taggeditem"."object_id",
"posthog_taggeditem"."object_uuid",
@@ -1327,19 +1288,6 @@
'''
SELECT "posthog_taggeditem"."id",
"posthog_taggeditem"."tag_id",
- "posthog_taggeditem"."dashboard_id",
- "posthog_taggeditem"."insight_id",
- "posthog_taggeditem"."event_definition_id",
- "posthog_taggeditem"."property_definition_id",
- "posthog_taggeditem"."action_id",
- "posthog_taggeditem"."feature_flag_id",
- "posthog_taggeditem"."experiment_saved_metric_id",
- "posthog_taggeditem"."ticket_id",
- "posthog_taggeditem"."account_id",
- "posthog_taggeditem"."endpoint_id",
- "posthog_taggeditem"."replay_scanner_id",
- "posthog_taggeditem"."project_id",
- "posthog_taggeditem"."experiment_id",
"posthog_taggeditem"."content_type_id",
"posthog_taggeditem"."object_id",
"posthog_taggeditem"."object_uuid",
diff --git a/posthog/test/repo_invariants/test_taggable_registry.py b/posthog/test/repo_invariants/test_taggable_registry.py
index 661f6964faf4..665ca1f16bbb 100644
--- a/posthog/test/repo_invariants/test_taggable_registry.py
+++ b/posthog/test/repo_invariants/test_taggable_registry.py
@@ -5,7 +5,7 @@ import pytest
from django.apps import apps
from django.db import models
-from posthog.models.tagged_item import RELATED_OBJECTS, TaggedItem
+from posthog.models.tagged_item import TaggedItem
from posthog.models.tagged_item_registry import (
OBJECT_ID,
OBJECT_UUID,
@@ -23,10 +23,6 @@ def _model_for(entry: TaggableModel) -> type[models.Model]:
return apps.get_model(entry.model_label)
-def test_registry_matches_the_foreign_key_fields() -> None:
- assert {entry.legacy_field for entry in TAGGABLE_MODELS} == set(RELATED_OBJECTS)
-
-
def test_registry_entries_are_unique() -> None:
labels = [entry.model_label for entry in TAGGABLE_MODELS]
legacy_fields = [entry.legacy_field for entry in TAGGABLE_MODELS]
@@ -50,11 +46,6 @@ def test_object_column_matches_the_primary_key_type(entry: TaggableModel) -> Non
)
[email protected]("entry", TAGGABLE_MODELS, ids=lambda entry: entry.legacy_field)
-def test_registry_points_at_the_same_model_as_the_foreign_key(entry: TaggableModel) -> None:
- assert TaggedItem._meta.get_field(entry.legacy_field).related_model is _model_for(entry)
-
-
@pytest.mark.parametrize("entry", TAGGABLE_MODELS, ids=lambda entry: entry.legacy_field)
def test_object_column_holds_the_primary_key_range(entry: TaggableModel) -> None:
"""`object_id` is a plain integer, so a bigint-keyed model must still fit inside it."""
diff --git a/posthog/test/test_migration_1370_backfill_taggeditem_generic_pointer.py b/posthog/test/test_migration_1370_backfill_taggeditem_generic_pointer.py
deleted file mode 100644
index ede9b6a26b70..000000000000
--- a/posthog/test/test_migration_1370_backfill_taggeditem_generic_pointer.py
+++ /dev/null
@@ -1,49 +0,0 @@
-from typing import Any
-
-from posthog.test.base import NonAtomicTestMigrations
-
-
-class BackfillTaggedItemGenericPointerTest(NonAtomicTestMigrations):
- migrate_from = "1369_taggeditem_legacy_reverse_accessors"
- migrate_to = "1373_taggeditem_generic_pointer_unique"
-
- def setUpBeforeMigration(self, apps: Any) -> None:
- tag_model = apps.get_model("posthog", "Tag")
- tagged_item_model = apps.get_model("posthog", "TaggedItem")
- dashboard_model = apps.get_model("dashboards", "Dashboard")
- event_definition_model = apps.get_model("event_definitions", "EventDefinition")
-
- self.tag_team_id = self.team.id
- tag = tag_model.objects.create(name="tag", team_id=self.team.id)
- self.dashboard = dashboard_model.objects.create(team_id=self.team.id, name="dashboard")
- self.event_definition = event_definition_model.objects.create(team_id=self.team.id, name="event")
-
- # Historical models skip TaggedItem.save(), so these rows start with no generic pointer,
- # like rows written before the pointer columns existed.
- self.dashboard_item = tagged_item_model.objects.create(tag=tag, dashboard_id=self.dashboard.id)
- self.event_definition_item = tagged_item_model.objects.create(
- tag=tag, event_definition_id=self.event_definition.id
- )
-
- def test_backfill_fills_the_generic_pointer(self) -> None:
- assert self.apps is not None
- tagged_item_model = self.apps.get_model("posthog", "TaggedItem")
- content_type_model = self.apps.get_model("contenttypes", "ContentType")
-
- dashboard_item = tagged_item_model.objects.get(pk=self.dashboard_item.pk)
- assert (
- dashboard_item.content_type_id
- == content_type_model.objects.get(app_label="dashboards", model="dashboard").id
- )
- assert dashboard_item.object_id == self.dashboard.id
- assert dashboard_item.object_uuid is None
- assert dashboard_item.team_id == self.tag_team_id
-
- event_definition_item = tagged_item_model.objects.get(pk=self.event_definition_item.pk)
- assert (
- event_definition_item.content_type_id
- == content_type_model.objects.get(app_label="event_definitions", model="eventdefinition").id
- )
- assert event_definition_item.object_uuid == self.event_definition.id
- assert event_definition_item.object_id is None
- assert event_definition_item.team_id == self.tag_team_id
diff --git a/products/actions/backend/api/test/__snapshots__/test_action.ambr b/products/actions/backend/api/test/__snapshots__/test_action.ambr
index 6e5d43d2341b..4db4f4c569f8 100644
--- a/products/actions/backend/api/test/__snapshots__/test_action.ambr
+++ b/products/actions/backend/api/test/__snapshots__/test_action.ambr
@@ -466,19 +466,6 @@
'''
SELECT "posthog_taggeditem"."id",
"posthog_taggeditem"."tag_id",
- "posthog_taggeditem"."dashboard_id",
- "posthog_taggeditem"."insight_id",
- "posthog_taggeditem"."event_definition_id",
- "posthog_taggeditem"."property_definition_id",
- "posthog_taggeditem"."action_id",
- "posthog_taggeditem"."feature_flag_id",
- "posthog_taggeditem"."experiment_saved_metric_id",
- "posthog_taggeditem"."ticket_id",
- "posthog_taggeditem"."account_id",
- "posthog_taggeditem"."endpoint_id",
- "posthog_taggeditem"."replay_scanner_id",
- "posthog_taggeditem"."project_id",
- "posthog_taggeditem"."experiment_id",
"posthog_taggeditem"."content_type_id",
"posthog_taggeditem"."object_id",
"posthog_taggeditem"."object_uuid",
@@ -1105,19 +1092,6 @@
'''
SELECT "posthog_taggeditem"."id",
"posthog_taggeditem"."tag_id",
- "posthog_taggeditem"."dashboard_id",
- "posthog_taggeditem"."insight_id",
- "posthog_taggeditem"."event_definition_id",
- "posthog_taggeditem"."property_definition_id",
- "posthog_taggeditem"."action_id",
- "posthog_taggeditem"."feature_flag_id",
- "posthog_taggeditem"."experiment_saved_metric_id",
- "posthog_taggeditem"."ticket_id",
- "posthog_taggeditem"."account_id",
- "posthog_taggeditem"."endpoint_id",
- "posthog_taggeditem"."replay_scanner_id",
- "posthog_taggeditem"."project_id",
- "posthog_taggeditem"."experiment_id",
"posthog_taggeditem"."content_type_id",
"posthog_taggeditem"."object_id",
"posthog_taggeditem"."object_uuid",
diff --git a/products/customer_analytics/backend/test/test_facade.py b/products/customer_analytics/backend/test/test_facade.py
index c535b2b787bf..ebf4bec9ff41 100644
--- a/products/customer_analytics/backend/test/test_facade.py
+++ b/products/customer_analytics/backend/test/test_facade.py
@@ -96,7 +96,7 @@ class TestCustomerAnalyticsFacade(BaseTest):
ignored_at = timezone.now()
account = create_account(team_id=self.team.id, name="Acme Corp", external_id="acme-123", ignored_at=ignored_at)
tag = Tag.objects.create(name="enterprise", team_id=self.team.id)
- TaggedItem.objects.create(tag=tag, account=account)
+ account.tagged_items.create(tag=tag)
notebook = Notebook.objects.create(
team=self.team,
created_by=self.user,
@@ -242,7 +242,7 @@ class TestCustomerAnalyticsFacade(BaseTest):
).model_dump(mode="json"),
)
tag = Tag.objects.create(name="enterprise", team_id=self.team.id)
- TaggedItem.objects.create(tag=tag, account=account)
+ account.tagged_items.create(tag=tag)
result = facade.get_external_account(self.team.id, "acme-1")
@@ -444,7 +444,7 @@ class TestCustomerAnalyticsCRUDFacade(BaseTest):
def test_create_account_sets_tags(self):
view = self._create(name="Tagged", tags=["enterprise", "priority"])
account = Account.objects.unscoped().get(id=str(view.id))
- assert sorted(TaggedItem.objects.filter(account=account).values_list("tag__name", flat=True)) == [
+ assert sorted(TaggedItem.objects.for_object(account).values_list("tag__name", flat=True)) == [
"enterprise",
"priority",
]
diff --git a/products/customer_analytics/backend/test/test_upsert_account.py b/products/customer_analytics/backend/test/test_upsert_account.py
index 037cf600b24c..b4575f929a80 100644
--- a/products/customer_analytics/backend/test/test_upsert_account.py
+++ b/products/customer_analytics/backend/test/test_upsert_account.py
@@ -30,7 +30,7 @@ class TestUpsertAccountTool(BaseTest):
async def _tags_for(self, account: Account) -> list[str]:
return await sync_to_async(
- lambda: sorted(TaggedItem.objects.filter(account=account).values_list("tag__name", flat=True))
+ lambda: sorted(TaggedItem.objects.for_object(account).values_list("tag__name", flat=True))
)()
@sync_to_async
diff --git a/products/customer_analytics/backend/test/test_views.py b/products/customer_analytics/backend/test/test_views.py
index 57876d094e25..8ca4e45004b0 100644
--- a/products/customer_analytics/backend/test/test_views.py
+++ b/products/customer_analytics/backend/test/test_views.py
@@ -949,7 +949,7 @@ class TestAccountViewSet(APIBaseTest):
["enterprise", "priority"],
)
self.assertEqual(
- sorted(TaggedItem.objects.filter(account=account).values_list("tag__name", flat=True)),
+ sorted(TaggedItem.objects.for_object(account).values_list("tag__name", flat=True)),
["enterprise", "priority"],
)
diff --git a/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambr b/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambr
index 153ac3034275..5bb261bb8e14 100644
--- a/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambr
+++ b/products/feature_flags/backend/api/test/__snapshots__/test_feature_flag.ambr
@@ -787,19 +787,6 @@
'''
SELECT "posthog_taggeditem"."id",
"posthog_taggeditem"."tag_id",
- "posthog_taggeditem"."dashboard_id",
- "posthog_taggeditem"."insight_id",
- "posthog_taggeditem"."event_definition_id",
- "posthog_taggeditem"."property_definition_id",
- "posthog_taggeditem"."action_id",
- "posthog_taggeditem"."feature_flag_id",
- "posthog_taggeditem"."experiment_saved_metric_id",
- "posthog_taggeditem"."ticket_id",
- "posthog_taggeditem"."account_id",
- "posthog_taggeditem"."endpoint_id",
- "posthog_taggeditem"."replay_scanner_id",
- "posthog_taggeditem"."project_id",
- "posthog_taggeditem"."experiment_id",
"posthog_taggeditem"."content_type_id",
"posthog_taggeditem"."object_id",
"posthog_taggeditem"."object_uuid",
diff --git a/products/feature_flags/backend/api/test/test_feature_flag.py b/products/feature_flags/backend/api/test/test_feature_flag.py
index 1f4b30312885..734865e0477b 100644
--- a/products/feature_flags/backend/api/test/test_feature_flag.py
+++ b/products/feature_flags/backend/api/test/test_feature_flag.py
@@ -11845,7 +11845,7 @@ class TestFeatureFlagEvaluationContexts(APIBaseTest):
flag = FeatureFlag.objects.get(key="flag-with-eval-tags")
# Check that tags are created
- tagged_items = TaggedItem.objects.filter(feature_flag=flag)
+ tagged_items = TaggedItem.objects.for_object(flag)
self.assertEqual(tagged_items.count(), 3)
tag_names = sorted([item.tag.name for item in tagged_items])
self.assertEqual(tag_names, ["app", "docs", "marketing"])
@@ -11938,7 +11938,7 @@ class TestFeatureFlagEvaluationContexts(APIBaseTest):
self.assertEqual(FeatureFlagEvaluationContext.objects.filter(feature_flag=flag).count(), 0)
# Regular tags should still exist
- tagged_items = TaggedItem.objects.filter(feature_flag=flag)
+ tagged_items = TaggedItem.objects.for_object(flag)
self.assertEqual(tagged_items.count(), 2)
@pytest.mark.ee
diff --git a/products/feature_flags/backend/test/test_max_tools.py b/products/feature_flags/backend/test/test_max_tools.py
index 200b9b924cd7..6dcb204e046b 100644
--- a/products/feature_flags/backend/test/test_max_tools.py
+++ b/products/feature_flags/backend/test/test_max_tools.py
@@ -620,6 +620,6 @@ class TestCreateFeatureFlagTool(APIBaseTest):
@database_sync_to_async
def get_tags():
- return list(TaggedItem.objects.filter(feature_flag=flag).values_list("tag__name", flat=True))
+ return list(TaggedItem.objects.for_object(flag).values_list("tag__name", flat=True))
return await get_tags()
diff --git a/products/product_analytics/backend/presentation/insight.py b/products/product_analytics/backend/presentation/insight.py
index 5b2eb4c226f6..d31cba0827bf 100644
--- a/products/product_analytics/backend/presentation/insight.py
+++ b/products/product_analytics/backend/presentation/insight.py
@@ -6,7 +6,7 @@ from typing import Any, Union, cast
from django.conf import settings
from django.db import transaction
-from django.db.models import Count, Exists, F, Max, OuterRef, QuerySet
+from django.db.models import Count, Exists, F, Max, QuerySet
from django.db.models.query_utils import Q
from django.utils.functional import SimpleLazyObject
from django.utils.timezone import now
@@ -2105,7 +2105,7 @@ class InsightViewSet(
if tags_list:
# A semi-join returns one row per insight, so the list needs no
# `.distinct()` sort over the wide insight JSON columns.
- matching_tags = TaggedItem.objects.filter(insight_id=OuterRef("pk"), tag__name__in=tags_list)
+ matching_tags = TaggedItem.objects.matching_outer(Insight).filter(tag__name__in=tags_list)
queryset = queryset.filter(Exists(matching_tags))
elif key == "created_by":
created_by_filter = request.GET["created_by"]
diff --git a/products/product_analytics/backend/tests/api/__snapshots__/test_insight.ambr b/products/product_analytics/backend/tests/api/__snapshots__/test_insight.ambr
index ffb357cadbd4..79461a3f8621 100644
--- a/products/product_analytics/backend/tests/api/__snapshots__/test_insight.ambr
+++ b/products/product_analytics/backend/tests/api/__snapshots__/test_insight.ambr
@@ -1298,19 +1298,6 @@
'''
SELECT "posthog_taggeditem"."id",
"posthog_taggeditem"."tag_id",
- "posthog_taggeditem"."dashboard_id",
- "posthog_taggeditem"."insight_id",
- "posthog_taggeditem"."event_definition_id",
- "posthog_taggeditem"."property_definition_id",
- "posthog_taggeditem"."action_id",
- "posthog_taggeditem"."feature_flag_id",
- "posthog_taggeditem"."experiment_saved_metric_id",
- "posthog_taggeditem"."ticket_id",
- "posthog_taggeditem"."account_id",
- "posthog_taggeditem"."endpoint_id",
- "posthog_taggeditem"."replay_scanner_id",
- "posthog_taggeditem"."project_id",
- "posthog_taggeditem"."experiment_id",
"posthog_taggeditem"."content_type_id",
"posthog_taggeditem"."object_id",
"posthog_taggeditem"."object_uuid",
@@ -1328,19 +1315,6 @@
'''
SELECT "posthog_taggeditem"."id",
"posthog_taggeditem"."tag_id",
- "posthog_taggeditem"."dashboard_id",
- "posthog_taggeditem"."insight_id",
- "posthog_taggeditem"."event_definition_id",
- "posthog_taggeditem"."property_definition_id",
- "posthog_taggeditem"."action_id",
- "posthog_taggeditem"."feature_flag_id",
- "posthog_taggeditem"."experiment_saved_metric_id",
- "posthog_taggeditem"."ticket_id",
- "posthog_taggeditem"."account_id",
- "posthog_taggeditem"."endpoint_id",
- "posthog_taggeditem"."replay_scanner_id",
- "posthog_taggeditem"."project_id",
- "posthog_taggeditem"."experiment_id",
"posthog_taggeditem"."content_type_id",
"posthog_taggeditem"."object_id",
"posthog_taggeditem"."object_uuid",
diff --git a/products/product_analytics/backend/tests/api/test_insight.py b/products/product_analytics/backend/tests/api/test_insight.py
index 669f8183f9e7..725fd7e4213a 100644
--- a/products/product_analytics/backend/tests/api/test_insight.py
+++ b/products/product_analytics/backend/tests/api/test_insight.py
@@ -846,14 +846,13 @@ class TestInsight(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
)
def test_list_does_not_duplicate_insights_with_multiple_matching_tags(self, _name: str, query: str) -> None:
from posthog.models.tag import Tag
- from posthog.models.tagged_item import TaggedItem
insight = Insight.objects.create(
short_id="search-tg", name="needle", team=self.team, filters={"events": [{"id": "$pageview"}]}
)
for tag_name in ("needle-tag-a", "needle-tag-b", "needle-tag-c"):
tag = Tag.objects.create(name=tag_name, team=self.team)
- TaggedItem.objects.create(insight=insight, tag=tag)
+ insight.tagged_items.create(tag=tag)
response = self.client.get(f"/api/projects/{self.team.id}/insights/?{query}")
assert response.status_code == status.HTTP_200_OK
diff --git a/products/replay_vision/backend/tests/test_api.py b/products/replay_vision/backend/tests/test_api.py
index 63d5501a676c..cd63c41691db 100644
--- a/products/replay_vision/backend/tests/test_api.py
+++ b/products/replay_vision/backend/tests/test_api.py
@@ -942,7 +942,7 @@ class TestReplayScannerTags(_VisionAPITestCase):
def _tag_names(self, scanner_id: str) -> list[str]:
return sorted(
- TaggedItem.objects.filter(replay_scanner_id=scanner_id).values_list("tag__name", flat=True),
+ TaggedItem.objects.for_objects(ReplayScanner, [scanner_id]).values_list("tag__name", flat=True),
)
@parameterized.expand(