Andrew Einhorn
Andrew Einhorn

Reputation: 1163

Can I use the same @property on multiple models in django?

I want to define an @property once and use it on two different models. Is this possible?

Example:

Suppose I have two models, seller and buyer:

class seller(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)

class buyer(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)

And I wish to add a property for the django admin interface to display both models:

@property
def display_name(self):
    return f"{first_name} {last_name}"

Is there a way to define this property once, but use it for both models?

Upvotes: 2

Views: 418

Answers (2)

Mohamed Hamza
Mohamed Hamza

Reputation: 985

Yes, you can do something like this:

class Base(models.Model): # Make it abstract to avoide repeating code
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)

    @property
    def display_name(self):
       return f"{self.first_name} {self.last_name}"

    class Meta:
          abstract = True

Then Inherit from it like this:

class seller(Base):
      pass

class buyer(Base):
      pass 

Upvotes: 1

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477240

You can define an abstract model that can define the first_name and last_name field as well as the property:

class Trader(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)

    @property
    def display_name(self):
        return f'{self.first_name} {self.last_name}'

    class Meta:
        abstract = True

and then make two concrete models with that:

class Buyer(Trader):
    pass

class Seller(Trader):
    pass

Here we thus do not only inherit the property, but the model fields as well.


If you do not want to inherit the fields, you can implement a mixin, so:

class NameMixin:

    @property
    def display_name(self):
        return f'{self.first_name} {self.last_name}'

and then mix it in the Buyer and Seller models:

class Seller(NameMixin, models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)

class Buyer(NameMixin, models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)

Upvotes: 3

Related Questions