Reputation: 1163
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
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
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