If for example, I have a class Summary,
each Instance of the class Summary, can be one subject:
subjects = (
('english', 'אנגלית'),
('bible', 'תנ"ך'),
('history', 'היסטוריה'),
('civics', 'אזרחות'),
('language', 'לשון'),
('literature', 'ספרות'),
)
class Summary(models.Model):
...
subject = models.CharField(max_length=20, choices=subjects)
...
Now I've decided I want to hardcode some topics for each subject, so if Summary.subject = "literature"
I want to add a field
subtopic = models.CharField(choices=literature_subtopics)
and make the choices equal to:
literature_subtopics = (
('poems', 'שירה'),
('short_stories', 'סיפורים קצרים'),
('plays', 'מחזות'),
('novels', 'נובלות'),
)
If the subject was English then english_subtopics
would be used for the choices field.
I want to hard-code all these divisions because they will not change more than once every few years if at all, storing them in a database makes zero sense.
I need to somehow set up all these divisions for each subject, and make Django set the choices field for the subtopic appropriately.
can I override the init method to accomplish this somehow? I heard that's a bad idea and can break things.
Even if the data doesn't change often, it seems most natural to put data in the database and Python in Python files. Your proposed solution seems like you're fighting the way Django wants to do things.
What do think of a database solution?
class Subject(models.Model):
parent = models.ForeignKey("self")
name = models.CharField(max_length=100)
hebrew_name = models.CharField(max_length=100)
class Summary(models.Model):
...
subject = models.ForeignKey("Subject")
...
class SubjectForm(forms.Form):
subject = forms.ModelChoiceField(queryset=Subject.objects.none())
...
def __init__(self, *args, **kwargs): # see http://stackoverflow.com/a/4880869/1477364
sub = kwargs.pop('parent_subject')
super(SubjectForm, self).__init__(*args, **kwargs)
parent_subject = Subject.objects.get(name=sub)
sub_subjects = Subject.objects.filter(parent=parent_subject)
self.fields['subject'].queryset = forms.ModelChoiceField(queryset=sub_subjects)
Note that the code implies there will always be a parent Subject passed to SubjectForm. (You'll need a "root" Subject.)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments