Search code examples
djangodjango-modelsmodels

User history actions - The proper way to store in django models


My users are employers who can make actions like sending messages to candidates, share their resume with other and write a review about a candidate.

For that I've created 3 seperate models, one for each action:

class Share(models.Model):
    user          = models.ForeignKey(BatitoUser, related_name="shares")
    shared_user   = models.ForeignKey(BatitoUser, blank=True)
    to_email      = models.EmailField()
    message       = models.TextField(blank=True)
    date          = models.DateTimeField(auto_now_add=True)

    def __unicode__(self):
        return '%s - %s' % (self.user, self.to_email)

class Review(models.Model):
   user    = models.ForeignKey(BatitoUser)
   to_user = models.ForeignKey(BatitoUser, related_name='reviews')
   review  = models.TextField(blank=True)
   rating  = models.DecimalField(max_digits=2, decimal_places=1, blank=True)
   date    = models.DateField(auto_now=True)

   def __unicode__(self):
        return '%s - %s' % (self.user, self.to_user)**

class MessageSent(models.Model):
     user    = models.ForeignKey(BatitoUser, related_name="messages")
     to_user = models.ForeignKey(BatitoUser)
     message = models.TextField()
     date = models.DateTimeField(auto_now_add=True)

     def __unicode__(self):
         return '%s - %s' % (self.user, self.to_user)

I would like to be able to list all employer's history actions. What is the best way to do so?

I was thinking about 2 options :

  1. Retrieving related info from each model into the template ( user.reviews_set.all , user.share_set.all ,etc...) And then sort them all by date via jquery/javascript.

  2. Create another history model that will contains all user actions. But I'm not sure how to do it...

I will appreciate any suggestions.


Solution

  • you can get inspired from django's admin log from django.contrib.admin.models import LogEntry or use it if it matches your requirements. Checkout this