I am implementing my first model requiring a many-to-many field. It’s proving to be the adventure I expected. Writing the post to get feedback on my approach and clarify details on how Django manages these model objects.
Here is the key field declaration:
speciesInstances = models.ManyToManyField (SpeciesInstance, related_name='species_maintenance_groups')
I have learned that speciesInstances cannot be accessed until the object is saved in the db. This led me to puzzle over how to best manage the Model Form for this field (editable, hidden, or read-only) and its associated validation. Excluding fields leads to skipping those fields with validation, while setting the field as disabled by overriding init in the model declaration leads to ‘immutable object’ errors accessing the parent object.
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._meta.fields.fields['speciesInstances'].disabled = True
I could possibly set the field to read-only (editable=False) but that also applies to the admin page which I don’t want.
speciesInstances = models.ManyToManyField(SpeciesInstance, editable=False, related_name='species_maintenance_groups')
So currently I am simply excluding this field from the associated Model Form and accepting that any validation checks and assignments to this field require custom code prior to saving to the db. Next up is implementing a custom query to narrow the set of speciesInstance objects suitable for editing (it’s very small compared to the very large .all() set) and figuring out the custom form to support user addition or removal from speciesInstances.
As I’m still a bit of a newbie I’m asking for feedback on my approach and any corrections to my assumptions on how things work.
Thanks!