[Django]-Using a Proxy Model when accessing foreign key

0đź‘Ť

The best solution I’ve come up with so far is to do something scary on the related model’s __init__:

class PersonFact(models.Model):
  fact = models.TextField()
  person = models.ForeignKey(Person, db_column="person_id")
  lightweight_person = models.ForeignKey(
     LightweightPerson, db_column="person_id", 
     related_name="lightweight_personfact_set")

def __init__(self, *args, **kw):
    models.Model.__init__(self, *args, **kw)
    index = None
    for i, field in enumerate(self._meta.local_fields):
        if field.name == 'lightweight_person':
            index = i
            break
    if index is not None:
        self._meta.local_fields.pop(index)

This apparently hides the existence of that field from the object manager for updates and inserts, so the “column specified more than once” error doesn’t occur; and the field still gets populated when I select existing data.

This seems to work, but it’s pretty scary — I have no idea if it will have side effects in other parts of my code.

👤ejucovy

Leave a comment