Is it possible to use proxy model instances for a foreign key?
Are there any downsides or risks to doing this?
Sample code:
base_models.py
class BaseWidget(models.Model):
name = models.CharField(max_length=100)
code = models.CharField(max_length=100)
class BasePart(models.Model):
name = models.CharField(max_length=100)
code = models.CharField(max_length=100)
widget = models.ForeignKey(BaseWidget, related_name="parts")
models.py
from base_models import BaseWidget, BasePart
class Part(BasePart):
class Meta:
proxy = True
class Widget(BaseWidget):
def replace_part(self, old_code, new_code):
self.parts.filter(code=old_code).delete()
self.parts.add(Part.objects.get(code=new_code))
class Meta:
proxy = True
Notice that in replace_part
it is adding a Part
, not a BasePart
. This is what I'm wondering -- whether this is acceptable to Django and, if so, if there are any hidden drawbacks or dangers to doing this.
It's perfectly acceptable. Just bear in mind, that like when using any child class instead of the parent, you're then limiting it to only that child and any children of it, even though in the scenario of proxy classes the child is basically the same as the parent.