Skip to content

Instantly share code, notes, and snippets.

@jordic
Created July 23, 2012 05:30
Show Gist options
  • Save jordic/3162079 to your computer and use it in GitHub Desktop.
Save jordic/3162079 to your computer and use it in GitHub Desktop.
Automatic ordering implementation in Django Models
###################################################
# #
# Default concrete implementations are below. #
# #
###################################################
class FormEntry(AbstractFormEntry):
form = models.ForeignKey("Form", related_name="entries")
class FieldEntry(AbstractFieldEntry):
entry = models.ForeignKey("FormEntry", related_name="fields")
class Form(AbstractForm):
pass
class Field(AbstractField):
"""
Implements automated field ordering.
"""
form = models.ForeignKey("Form", related_name="fields")
order = models.IntegerField(_("Order"), null=True, blank=True)
class Meta(AbstractField.Meta):
ordering = ("order",)
def save(self, *args, **kwargs):
if self.order is None:
self.order = self.form.fields.count()
super(Field, self).save(*args, **kwargs)
def delete(self, *args, **kwargs):
fields_after = self.form.fields.filter(order__gte=self.order)
fields_after.update(order=models.F("order") - 1)
super(Field, self).delete(*args, **kwargs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment