Miguel Rosales
Miguel Rosales

Reputation: 799

Django model audit mixin

Hello I wanted to know how to create a few fields and convert them into a mixin.

Let's say I have the following.

class Supplier(models.Model):
    name = models.CharField(max_length=128)
    created_by = models.ForeignKey(get_user_model(), related_name='%(class)s_created_by')
    modified_by = models.ForeignKey(get_user_model(), related_name='%(class)s_modified_by')
    created_date = models.DateTimeField(editable=False)
    modified_date = models.DateTimeField()

    def save(self, *args, **kwargs):
        if not self.id:
            self.created_date = timezone.now()
        self.modified_date = timezone.now()
        return super(Supplier, self).save(*args, **kwargs)

I want to create a mixin to avoid writing every time the last 4 fields into different models.

Here is the mixin I would create:

class AuditMixin(models.Model):
    created_by = models.ForeignKey(get_user_model(), related_name='%(class)s_created_by')
    modified_by = models.ForeignKey(get_user_model(), related_name='%(class)s_modified_by')
    created_date = models.DateTimeField(editable=False)
    modified_date = models.DateTimeField()


   def save(self, *args, **kwargs):
       if not self.id:
           self.created_date = timezone.now()
       self.modified_date = timezone.now()
       return super(Supplier, self).save(*args, **kwargs)

class Supplier(AuditMixin):
    name = models.Charfield(max_length=128)

How can I make sure that the related_name is relevant to the class the mixin is included into? Also in the save function, How can I make sure the class the mixin is included into is returned (as per the last line)?

Thank you!

Upvotes: 0

Views: 847

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599630

Firstly, in any super call, you must always use the current class. So it will always be super(AuditMixin, self)... and your question does not apply.

Django itself takes care of substituting the current class name in related_name if you use the %(class)s syntax, which you have, so again there is nothing else for you to do. See the model inheritance docs.

Upvotes: 2

Related Questions