I have a django project that currently has two apps: one that contains the data for a directory site, and one that provides support functionality for importing the data in the directory site. I want them to be loosely coupled. The support app should be driving the data app. The data app, and its models, shouldn’t be driving the support app.
A problem I ran into is this: I want a record of an import to remain, even if the imported record is deleted. But, since I used a ForeignKey, and Django has cascading deletes, the record of the import would be deleted. I searched for a way to turn off this behavior, and found two options:
- Clear the ForeignKey reference to the imported record in the record of the import before deleting the imported record
- Use a ManyToManyField instead
At first, I used the first option. I saw the second option, but skipped it because it seemed overkill. Something didn’t sit well with having to clear a field before deleting, though. So, weeks later, I searched again, and was reminded of the ManyToManyField option.
The ManyToManyField option is a trade-off. On one hand, it fixes my coupling issues. On the other hand, it adds an extra table to my support class, and is overkill for something that only needs zero or one instances of the model associated with it. In this case, I chose the ManyToManyField option.
I’m quite happy with my new choice, and I think I might have chose it earlier if I hadn’t immediately discounted one approach and listed the pros and cons of each approach first.