1

I have a model with a ManyToMany field, and everytime I create an object I need to search the database for more objects with the same phone or email created previously.

Right now, I am using a post_save signal to do this, but I wanted to know if there is a better way to do this, maybe on the creation serializer.

class Leads(models.Model):
      name = models.CharField(max_lenght=40)
      phone = models.CharField(max_lenght=14)
      email = models.EmailField()
      other_leads = models.ManyToManyField('Leads')
      created = models.DateTimeField(auto_now_add)


 @receiver(post_save, sender=Leads)
 def add_related(sender, instance, created, **kwargs)
      if created:
          [instance.other_leads.add(lead) for lead in Leads.objects.filter(email=instance.email, created__lt=instance.created)]
Stargazer
  • 1,442
  • 12
  • 19

1 Answers1

2

Having a signal handler is fine. However, you should never use a comprehension for its side effects if you don't use its value. Just use a common loop! There are no prices to be won for one less line, but there are many downsides in terms of readability, maintainability, and space efficiency. Moreover, you can pass multiple instances to add at once:

if created:
    instance.other_leads.add(*Leads.objects.filter(
        email=instance.email, 
        created__lt=instance.created))
user2390182
  • 72,016
  • 6
  • 67
  • 89