Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Send message to all Users in Django

i was about to create a function that sends message to all members Using forloop
but then i thought that this method gonna take alot of time in process if there is a plenty of members…

so i came to ask if is there any better method to ignore forloop and smooth the process.

Model:

class TblExamNotification(models.Model):

    exam = ForeignKey(TblExam,on_delete=models.CASCADE,blank=True, null=True)
    user = ForeignKey(Members,on_delete=models.CASCADE,blank=True, null=True)
    is_seen = BooleanField(default=False)

    def __str__(self):
        return str(self.id)

Views:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

for member in memebers.exclude(member = request.user):
           notif_obj = Members.objects.create(user=member , exam=exam_obj)
           notif_obj .save()

>Solution :

First create a list of all notifications you want to use, then save these in bulk with bulk_create(…) [Django-doc]:

items = [
    TblExamNotification(user=member , exam=exam_obj)
    for member in memebers.exclude(member=request.user)
]

TblExamNotification.objects.bulk_create(items)

The bottleneck is (very) likely not the for loop itself, but the fact that you used a lot of queries to the database.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading