Python - you can't use property() with a classmethod
Not that it's a particularly common use case, I suppose, but still, it's worth noting. I was trying to use a Scala paradigm (computed values) in Python, so I'm not surprised. The code that failed:
class Category(models.Model): title = models.CharField(max_length = 50, unique = True)
uncategorizedTitle = "Uncategorised"
@classmethod def getUncategorised(cls): uncategorizedList = Category.objects.all().filter(title=cls.uncategorizedTitle) if uncategorizedList: return uncategorizedList[0] else: uncategorized = Category(title=Category.uncategorizedTitle) uncategorized.save() return uncategorized
uncategorised = property(fset=getUncategorised)
class BlogEntry(models.Model):
category = models.ForeignKey(Category, blank=True, null = True)
def save(self): if not self.category: self.category = Category.uncategorised
super(BlogEntry, self).save()
Removing the property and just calling the method directly works as expected. Admittedly, doing it as a property was entirely unnecessary syntactic sugar, no doubt stemming from the semantic connotations that I associate with the Enum.SpecificSubType syntax.
For an explanation of what I mean by a computed value, here's a pseudo-Scala transliteration of the Category code (without the pretty colours, unfortunately):
class Category extends models.Model {
var title = new models.CharField(50, True)
}
object Category {
val uncategorisedTitle = "Uncategorised"
let uncategorised = {
Category.objects.all().filter(title == uncategorisedTitle) match {
Nil => {
uncategorised = new Category(Map("title" -> "uncategorisedTitle"))
uncategorised.save()
uncategorised
}
first :: _ => {
first
}
}
}
}