ersran9
ersran9

Reputation: 978

Implementing unread/read checking for a message

I'm having a message model. To this model I want to add a read/unread field, which I did by using a boolean field. Now, if someone reads this message, I want this boolean field to be turned to true. I access these messages at different parts in my app, so updating the field manually is going to be tedious.

Is there any way I can get some messages according to some condition, and when the message is fetched from db, the field gets auto updated?

Upvotes: 0

Views: 1898

Answers (2)

Aidan Ewen
Aidan Ewen

Reputation: 13308

Why don't you create a read_message() method on a custom model manager. Have this method return the messages you want, whilst also updating the field on each message returned.

You new method allow you to replace Message.objects.get() with Message.objects.read_message()

class MessageManager(models.Manager):
    def read_message(self, message_id):
        # This won't fail quietly it'll raise an ObjectDoesNotExist exception
        message = super(MessageManager, self).get(pk=message_id)
        message.read = True
        message.save()
        return message

Then include the manager on your model -

class Message(models.Model):
    objects = MessageManager()

Obviously you could write other methods that return querysets whilst marking all the messages returned as read.

If you don't want to update your code (places where you call Message.objects.get()), then you could always actually override get() so that it updates the read field. Just replace the read_message function name above with get.

Upvotes: 2

lightningmanic
lightningmanic

Reputation: 2165

Depending on your database management system, you may be able to install a trigger:

PostgreSQL: http://www.postgresql.org/docs/9.1/static/sql-createtrigger.html

MySQL: http://dev.mysql.com/doc/refman/5.0/en/triggers.html

SQLite: http://www.sqlite.org/lang_createtrigger.html

Of course, this will need to be done manually in the database - outside of the Django application.

Upvotes: 1

Related Questions