Search code examples
mysqldjangopython-3.xdjango-notification

How to get push-notification in django when database has been updated with a new entry?


I want to generate a push-notification whenever the database entry is updated if the current ID is 2 and a new tuple is added the id would be 3. so how can i be notified if that new id has been added to the database?

The data entry is done on the back-end by some python script no data has been added to the MySQL database by the user.

So every time a new tuple is added to the database I want my application to give me notification.

I am posting everything that might be relevant for your ease. please hep me with the code.

models.py creates table Offenses in the database models.py

class Offenses(models.Model):
    oid = models.IntegerField(primary_key=True)
    description = models.CharField(null=False, max_length=200)


    objects = UserManager()
    class Meta:
        db_table = "offenses"

from views.py i am adding entries to the database that has been retrieved from an API and stored in the database.here is the snippet of my views.py

response_body = json.loads(response.read().decode('utf-8'))
    for j in response_body:
        obj, created = Offenses.objects.get_or_create(oid=j['id'], defaults={'description': j['description'], 'assigned_to': j['assigned_to']})



    return render(request, 'table.html')

Solution

  • You could do something like this:

    class Offenses(models.Model):
        oid = models.IntegerField(primary_key=True)
        description = models.CharField(null=False, max_length=200)
    
        objects = UserManager() # Don't know why you use a user manager here.
    
        class Meta:
            db_table = "offenses"
    
        def save(self, force_insert=False, force_update=False, using=None,
                 update_fields=None):  # Overriding the model save function.
            if self.id is None:  # A none id indicates that it is a new object.
                pass  # Send / store the notification.
    
            super().save(force_insert, force_update, using, update_fields)
    

    How to do a push notification system it is another topic, but with this logic you can save the notification when the object is going to be created.