user16858520
user16858520

Reputation:

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:

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

Upvotes: 1

Views: 495

Answers (2)

Msv
Msv

Reputation: 1371

The issue is not with for loop. The issue is you are making DB query on every creation of the Members object.

You can reduce multiple hits using bulk create which makes query only once to create multiple objects.

Ref: Bulk create

member_objs = [Members(user=member, exam=exam_obj) for member in members.exclude(member=request.user)]
Members.objects.bulk_create(member_objs)

Upvotes: 1

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476699

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.

Upvotes: 1

Related Questions