Reputation: 537
I am running a process to migrate a lot of call data. I have a model representing a phone line, and another model representing a caller. A phone line can have more than one caller, and a caller can phone more than one phone line. So a many to many relation is needed.
For 442/444 of the phone lines, the code below works and the caller is created and linked to a phone line or added to the relation.
However, in 2 cases duplicates are being created. That is, the phone line will store two caller instances with the same number.
How can I prevent this?
class Caller(models.Model):
number = models.CharField(max_length=20)
phoneline = models.ManyToManyField(
PhoneLine,
related_name="callers"
)
class PhoneLine(models.Model):
number = models.CharField(
max_length=20,
default=""
)
try:
caller = Caller.objects.get(number=number)
except ObjectDoesNotExist:
caller = Caller.objects.create(number=number)
caller.save()
if not caller.phoneline.filter(pk=phoneline.pk).exists():
caller.phoneline.add(phoneline)
Upvotes: 0
Views: 55
Reputation:
Change your code to
caller, created = Caller.objects.get_or_create(number=number)
caller.phoneline.add(phoneline)
get_or_create
method doc.
Django many to many field automatically check duplicate and if exists, not create.
Upvotes: 1