Skip to content
TheChatArchiveThe Chat Archive
DeepSeekdeepseek-r1-0528· DeepSeekHugging Face LMArena Human Preference 140K

class ContactGroupMember(DateTimeStamp): contactgroup = models.ForeignKey( ContactGroup,…

  1. 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_number
    

    class 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.name
    

    I 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.

  2. DeepSeek 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:

    1. Add full_name to ContactGroupMember: 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 ...
    
    1. 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}"
    
    1. 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 in ContactGroupMember:

    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:

    1. Check for existing phone numbers in the target group.
    2. Create new IndividualContact if phone number doesn't exist in the workspace.
    3. 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:

    1. Group-Specific Names: ContactGroupMember.full_name stores names specific to a group.
    2. Uniqueness Enforcement: Application logic prevents duplicate phone numbers per group.
    3. Import Behavior: New contacts are created for unrecognized numbers; existing contacts get group-specific names.
    4. 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.