Django empty field

I have a model containing a user address. This model should have the fields first_name and last_name, since you want to specify the address of the recipient (for example, his company, etc.). I am trying to achieve:

  • if the fist_name / last_name field in the address is filled in - just return this field
  • if the fist_name / last_name field in the address is empty - select the corresponding field data from a foreign key pointing to the corresponding django.auth.models.User
  • I would like this to be considered as a normal django field that will be present when searching for fields.
  • I don’t want to create a method, because it is refactored and Address.first_name / last_name is used in different places of the application (also in model forms, etc.), so I need this for me as smooth as possible or I will have to mess around in many places .

Thanks for the help:)

+4
source share
2 answers

There are two options. The first is to create a method for dynamic search, but use a decorator propertyso that other code can still use direct access to the attributes.

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 always refers to the last value of first_name, even if the associated User has changed. You can get / set the property in the same way as for the attribute:myinstance.first_name = 'daniel'

Another option is to override the model method save()so that it performs a search while saving:

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)

, db, - , User , , .

+6

OP, , ( ) , Django Coalesce() (docs).

( @daniel-roseman):

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

, user.

, , , property.

( ) SO.

0

Source: https://habr.com/ru/post/1716240/


All Articles