开发者

Django Zero Value on ForeignKey Field

I'm working on very badly designed legacy databas开发者_开发问答e. 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.


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.


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]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜