Django Model Field Default Based Off Another Field in Same Model

前端 未结 4 1718
挽巷
挽巷 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:30

    Using Django signals, this can be done quite early, by receiving the post_init signal from the model.

    from django.db import models
    import django.dispatch
    
    class LoremIpsum(models.Model):
        name = models.CharField(
            "Name",
            max_length=30,
        )
        subject_initials = models.CharField(
            "Subject Initials",
            max_length=5,
        )
    
    @django.dispatch.receiver(models.signals.post_init, sender=LoremIpsum)
    def set_default_loremipsum_initials(sender, instance, *args, **kwargs):
        """
        Set the default value for `subject_initials` on the `instance`.
    
        :param sender: The `LoremIpsum` class that sent the signal.
        :param instance: The `LoremIpsum` instance that is being
            initialised.
        :return: None.
        """
        if not instance.subject_initials:
            instance.subject_initials = "".join(map(
                    (lambda x: x[0] if x else ""),
                    instance.name.split(" ")))
    

    The post_init signal is sent by the class once it has done initialisation on the instance. This way, the instance gets a value for name before testing whether its non-nullable fields are set.

提交回复
热议问题