class ContactGroupMember(DateTimeStamp): contactgroup = models.ForeignKey( ContactGroup,…
- User
class ContactGroupMember(DateTimeStamp): contact_group = models.ForeignKey( ContactGroup, on_delete=models.CASCADE, related_name="group_memberships" ) contact = models.ForeignKey( IndividualContact, on_delete=models.CASCADE, related_name="contact_memberships" )
role = models.CharField(max_length=100, blank=True, null=True) notes = models.TextField(blank=True, null=True) class Meta: unique_together = ("contact_group", "contact") # Prevent duplicate members verbose_name = "Contact Group Member" verbose_name_plural = "Contact Group Members" def __str__(self): return f"{self.contact.full_name} in {self.contact_group.name}"class IndividualContact(DateTimeStamp): full_name = models.CharField(max_length=255) email = models.EmailField(blank=True, null=True) phone_number = models.CharField(max_length=20)
organization = models.CharField(max_length=255, blank=True, null=True) position = models.CharField(max_length=255, blank=True, null=True) hazard_focus = models.ManyToManyField("Hazard", blank=True, related_name="contacts") notes = models.TextField(blank=True, null=True) profile_picture = models.ImageField( upload_to="contacts/profile_images", blank=True, null=True ) thumbnail = models.ImageField( upload_to="contacts/profile_thumbnails", editable=False, null=True, blank=True ) workspace_id = models.IntegerField(null=True, blank=True) project_id = models.IntegerField(null=True, blank=True) def make_thumbnail(self): """ Create a thumbnail for the profile image """ if not self.profile_picture: return False try: # Open the image image = Image.open(self.profile_image) # Resize the image for thumbnail image.thumbnail((200, 150), Image.LANCZOS) # Prepare thumbnail filename thumb_name, thumb_extension = os.path.splitext(self.profile_image.name) thumb_filename = thumb_name + "_thumb.jpg" # Save thumbnail to in-memory file temp_thumb = BytesIO() image.convert("RGB").save(temp_thumb, format="JPEG") temp_thumb.seek(0) # Save thumbnail self.thumbnail.save( thumb_filename, ContentFile(temp_thumb.read()), save=False ) temp_thumb.close() return True except Exception: return False class Meta: unique_together = ("phone_number", "workspace_id") def __str__(self): return self.phone_numberclass ContactGroup(DateTimeStamp): name = models.CharField(max_length=255) group_type = models.CharField(max_length=50, choices=GroupType.choices) hazard_focus = models.ManyToManyField( "Hazard", blank=True, related_name="contact_groups" ) members = models.ManyToManyField( IndividualContact, through="ContactGroupMember", related_name="groups" ) notes = models.TextField(blank=True, null=True) workspace_id = models.IntegerField(null=True, blank=True) project_id = models.IntegerField(null=True, blank=True)
def save(self, *args, **kwargs): if self.project_id and not self.workspace_id: try: project = Project.objects.get(id=self.project_id) self.workspace_id = project.workspace.id except Project.DoesNotExist: raise ValidationError("Invalid project_id: No such project exists.") super().save(*args, **kwargs) class Meta: unique_together = ("name", "workspace_id") def __str__(self): return self.nameI have this requirement of making contact group and phone number uniqure togther. the issue i have now is , when i have the same individual contacts in differnt contact group, it is using the same name that i had renamed in contact group 1 instead of the one from the file that i upload to create contacts in group B.
Assistant
To address your requirement of ensuring uniqueness for the combination of contact group and phone number, and resolving the issue of contact names being overwritten across groups, follow these steps:
Step-by-Step Solution:
- Add
full_nametoContactGroupMember: This allows storing a group-specific name override for each contact within a group.
class ContactGroupMember(DateTimeStamp): contact_group = models.ForeignKey( ContactGroup, on_delete=models.CASCADE, related_name="group_memberships" ) contact = models.ForeignKey( IndividualContact, on_delete=models.CASCADE, related_name="contact_memberships" ) full_name = models.CharField(max_length=255, blank=True, null=True) # Group-specific name # ... other fields ...- Update
__str__to Use Override Name: Display the group-specific name if available, falling back to the contact's default name.
def __str__(self): display_name = self.full_name if self.full_name else self.contact.full_name return f"{display_name} in {self.contact_group.name}"- Enforce Group + Phone Number Uniqueness: Add a database constraint to prevent duplicate phone numbers within the same group.
class Meta: constraints = [ models.UniqueConstraint( fields=['contact_group', 'contact__phone_number'], name='unique_phone_per_group' ) ]Note: Django doesn't support cross-table constraints directly. Instead, handle this in the application logic:
Application Logic for Uniqueness Check:
Override the
save()method inContactGroupMember:def save(self, *args, **kwargs): # Check if another membership exists in the same group with the same phone number if ContactGroupMember.objects.filter( contact_group=self.contact_group, contact__phone_number=self.contact.phone_number ).exclude(pk=self.pk).exists(): raise ValidationError("A contact with this phone number already exists in the group.") super().save(*args, **kwargs)Import Process Adjustment:
When importing contacts into a group:
- Check for existing phone numbers in the target group.
- Create new
IndividualContactif phone number doesn't exist in the workspace. - Use group-specific name from the import file for the
ContactGroupMember.full_name.
# Example import logic: for row in import_data: contact, created = IndividualContact.objects.get_or_create( phone_number=row['phone'], workspace_id=group.workspace_id, defaults={'full_name': row['name'], ...} ) ContactGroupMember.objects.create( contact_group=group, contact=contact, full_name=row['name'] # Always use imported name for this group )Key Changes Summary:
- Group-Specific Names:
ContactGroupMember.full_namestores names specific to a group. - Uniqueness Enforcement: Application logic prevents duplicate phone numbers per group.
- Import Behavior: New contacts are created for unrecognized numbers; existing contacts get group-specific names.
- Data Integrity: Default contact details remain intact while allowing group overrides.
This solution ensures:
- Phone numbers are unique within each contact group.
- Names can vary for the same contact across different groups.
- Existing data integrity is preserved with minimal model changes.
- Add