1

I'm working on very badly designed legacy database. On some of the tables not only can the foreign keys be null (which is OK) they can be 0 too.

I mapped one of these tables to a Model it returns the desired None value when it is Null in the table but raises an exception when the value is 0.

Is there a way to make it return None on foreign keys containing the value 0.

Siavash
  • 358
  • 1
  • 5
  • 19

2 Answers2

0

Faced the same problem, so end up with writing ForeignKey subclass:

class LegacyForeignKey(models.ForeignKey):
    """
    ForeignKey for legacy databases where foreign keys columns
    are non-nullable and using zero values as NULL.

    class Order(models.Model):
        carrier = LegacyForeignKey('Carrier', null=True)
        class Meta:
           managed = False
           db_table = "ps_order"

    order.carrier_id = 0
    order.carrier  # no Carrier.DoesNotExist exception
    """

    def get_local_related_value(self, instance):
        ret = super().get_local_related_value(instance)
        return [None if item == 0 else item for item in ret]
vsvasya
  • 657
  • 6
  • 11
0

You'd have to create your own ForeignKey-like field that would not choke on a 0. Note that any non-NULL value could be valid, so your data is in the wrong here, and you should consider repairing it.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358