Django empty field fallback

前端 未结 2 2096
小鲜肉
小鲜肉 2021-01-02 15:17

I have a model that holds user address. This model has to have first_name and last_name fields since one would like to set address to a recipient (

2条回答
  •  清歌不尽
    2021-01-02 15:35

    Although this does not meet all the OP's requirements, in some use-cases where the fallback is needed in queryset filters (on the database level) it may be possible to use Django's Coalesce() class (docs).

    The simplest solution in such a case might be queryset annotation (using the example from @daniel-roseman's answer):

    queryset = MyModel.objects.annotate(first_name=Coalesce('_first_name', 'user__first_name'))

    Each item obtained from the queryset will then get a first_name attribute, which has the value of _first_name with a fallback (in case the value is null) to user.first_name.

    That is, assuming your model has as user relation.

    This can be implemented e.g. in a custom manager and could also be used in conjunction with a property approach.

    A detailed example for a similar case (override instead of fallback) is provided in this SO answer.

提交回复
热议问题