Django empty field fallback

前端 未结 2 2073
小鲜肉
小鲜肉 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:42

    There are two options here. The first is to create a method to look it up dynamically, but use the property decorator so that other code can still use straight attribute access.

    class MyModel(models.Model):
        _first_name = models.CharField(max_length=100, db_column='first_name')
    
        @property
        def first_name(self):
            return self._first_name or self.user.first_name
    
        @first_name.setter
        def first_name(self, value):
           self._first_name = value
    

    This will always refer to the latest value of first_name, even if the related User is changed. You can get/set the property exactly as you would an attribute: myinstance.first_name = 'daniel'

    The other option is to override the model's save() method so that it does the lookup when you save:

    def save(self, *args, **kwargs):
        if not self.first_name:
            self.first_name = self.user.first_name
        # now call the default save() method
        super(MyModel, self).save(*args, **kwargs)
    

    This way you don't have to change your db, but it is only refreshed on save - so if the related User object is changed but this object isn't, it will refer to the old User value.

提交回复
热议问题