Reputation:
Say I have 2 models:
User
Customer
They both have the following SHARED fields:
First name
Last name
Pin code
Id
They also have a shared save() method:
def save(self, *args, **kwargs):
if not self.pk:
id = secrets.token_urlsafe(8)
while User.objects.filter(id=id).count() != 0:
id = secrets.token_urlsafe(8)
self.id = id
super(User, self).save(*args, **kwargs)
How could I create a Base model that they can extend so that I don't need to define all of these things twice? Thanks!!
Upvotes: 3
Views: 1184
Reputation: 476624
You can make an abstract base class [Django-doc] that implements the common logic, and then inherit:
class MyBaseClass(models.Model):
id = models.CharField(max_length=8, primary_key=True)
first_name = models.CharField(max_length=128)
last_name = models.CharField(max_length=128)
pin_code = models.CharField(max_length=128)
def save(self, *args, **kwargs):
model = self._meta.model
if not self.pk:
id = secrets.token_urlsafe(8)
while model.objects.filter(id=id).exists():
id = secrets.token_urlsafe(8)
self.id = id
super().save(*args, **kwargs)
class Meta:
abstract = True
class User(MyBaseClass):
pass
class Customer(MyBaseClass):
pass
An abstract class will thus not construct a table, it basically is used to inherit fields, methods, etc. to avoid rewriting the same logic twice.
Upvotes: 2