Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
def create_preview_model(cls):
"Create a preview model for a PreviewModel"
name = cls.__name__ + "Preview"
#Set up a dictionary to simulate declarations within a class
attrs = {
'__module__': cls.__module__,
#OneToOne to the model we are previewing
attrs['preview_parent'] = models.OneToOneField(cls, related_name='preview')
attrs['__str__'] = preview_string
#duplicate all fields into this class, set your dependencies if any
cls.dependencies = []
for field in cls._meta.fields:
if != "preview_state":
if isinstance(field, (ForeignKey, OneToOneField, ManyToManyField)):
field_class = type(field)
rel = field.rel
field_dict = { "unique": field.unique,
"null": field.null,
"blank": field.blank
if rel.related_name:
field_dict["related_name"] = "preview" + rel.related_name
attrs[] = field_class(, **field_dict)
#if the dependency is a PreviewModel we will notify it of the model's current status
dependency_fields = [ for f in]
is_required = not field.blank and (not field.null or isinstance(field, ManyToManyField))
if "preview_state" in dependency_fields and is_required:
attrs[] = field
#create the new class and set it on the PreviewModel class for later access
new_class = type(name, (models.Model,), attrs)
cls.preview_class = new_class
return new_class
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment