+class Embed(models.Model):
+ embedder_content_type = models.ForeignKey(ContentType, related_name="embedder_related")
+ embedder_object_id = models.PositiveIntegerField()
+ embedder = generic.GenericForeignKey("embedder_content_type", "embedder_object_id")
+
+ embedded_content_type = models.ForeignKey(ContentType, related_name="embedded_related")
+ embedded_object_id = models.PositiveIntegerField()
+ embedded = generic.GenericForeignKey("embedded_content_type", "embedded_object_id")
+
+ def delete(self):
+ # This needs to be called manually.
+ super(Embed, self).delete()
+
+ # Cycle through all the fields in the embedder and remove all references
+ # to the embedded object.
+ embedder = self.embedder
+ for field in embedder._meta.fields:
+ if isinstance(field, EmbedField):
+ attr = getattr(embedder, field.attname)
+ setattr(embedder, field.attname, attr.replace(self.get_embed_tag(), ''))
+
+ embedder.save()
+
+ def get_embed_tag(self):
+ """Convenience function to construct the embed tag that would create this instance."""
+ ct = self.embedded_content_type
+ return "{%% embed %s.%s %s %%}" % (ct.app_label, ct.model, self.embedded_object_id)
+
+ class Meta:
+ app_label = 'penfield'
+
+
+def sync_embedded_instances(model_instance, embedded_instances):
+ model_instance_ct = ContentType.objects.get_for_model(model_instance)
+
+ # Cycle through all the embedded instances and make sure that they are linked to
+ # the model instance. Track their pks.
+ new_embed_pks = []
+ for embedded_instance in embedded_instances:
+ embedded_instance_ct = ContentType.objects.get_for_model(embedded_instance)
+ new_embed = Embed.objects.get_or_create(embedder_content_type=model_instance_ct, embedder_object_id=model_instance.id, embedded_content_type=embedded_instance_ct, embedded_object_id=embedded_instance.id)[0]
+ new_embed_pks.append(new_embed.pk)
+
+ # Then, delete all embed objects related to this model instance which do not relate
+ # to one of the newly embedded instances.
+ Embed.objects.filter(embedder_content_type=model_instance_ct, embedder_object_id=model_instance.id).exclude(pk__in=new_embed_pks).delete()
+
+