[Answered ]-Nice pythonic way to specify django model field choices with extra attributes and methods

2👍

I think the most natural way of handling this in Django would be to create a custom model field. You would use it like so:

class Reminder(models.Model):
    frequency = models.FrequencyField()
    next_reminder = models.DateTimeField()

reminder = Reminder.objects.get()
reminder_time = reminder.frequency.get_next_reminder_time()

To implement it, review the relevant documentation. Briefly, you’d probably:

  • Inherit from CharField
  • Supply the choices in the field definition
  • Implement get_prep_value(). You could represent values as actual class names, like you have above, or by some other value and use a lookup table.
  • Implement to_python(). This is where you’ll convert the database representation into an actual Python instance of your classes.

It’s a little more involved than that, but not much.

(The above assumes that you want to define the behavior in code. If you need to configure the behavior by supplying configuration values to the database (as you suggested above with the ForeignKey idea) that’s another story.)

Leave a comment