Django Model Field Default Based Off Another Field in Same Model

前端 未结 4 1728
挽巷
挽巷 2020-11-27 13:48

I have a model that I would like to contain a subjects name and their initials (he data is somewhat anonymized and tracked by initials).

Right now, I wrote

<         


        
4条回答
  •  误落风尘
    2020-11-27 14:21

    As an alternative implementation of Gabi Purcaru's answer, you can also connect to the pre_save signal using the receiver decorator:

    from django.db.models.signals import pre_save
    from django.dispatch import receiver
    
    
    @receiver(pre_save, sender=Subject)
    def default_subject(sender, instance, **kwargs):
        if not instance.subject_init:
            instance.subject_init = instance.subject_initials()
    

    This receiver function also takes the **kwargs wildcard keyword arguments which all signal handlers must take according to https://docs.djangoproject.com/en/2.0/topics/signals/#receiver-functions.

提交回复
热议问题