I am currently working on a project using Django Rest Framework and Postman. My objective is to assign existing contacts to a task. However, when I make a POST request via Postman, I receive the error: “contact with this email already exists”
The email field in my Contact model is defined as models.EmailField(unique=True), as I need to ensure that each email is unique across all contacts.
When I attempt to assign an existing contact to a task using a POST request, I receive the aforementioned error.
Here’s the relevant part of my code:
http://127.0.0.1:8000/tasks/
{
"id": null,
"title": "Postman",
"description": "Postman",
"dueTo": "2024-06-12T12:04:28Z",
"created": "2024-06-12T12:04:31Z",
"updated": "2024-06-12T12:04:34Z",
"priority": "LOW",
"category": "TECHNICAL_TASK",
"status": "TO_DO",
"subtasks": [
{
"id": null,
"description": "Postman",
"is_done": false
}
],
"contacts": [
{
"id": 1,
"email": "[email protected]",
"name": "Max Mueller",
"phone_number": "123456789",
"avatar_color": "#abcdef"
}
]
}
models.py
class Contact(models.Model):
id = models.AutoField(primary_key=True)
email = models.EmailField(unique=True)
name = models.CharField(max_length=50)
phone_number = models.CharField(max_length=30)
avatar_color = models.CharField(max_length=7)
def __str__(self):
return f"{self.name}"
serialzers.py
class ContactSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Contact
fields = ['id', 'email', 'name', 'phone_number', 'avatar_color']
models.py
class Task(models.Model):
id = models.AutoField(primary_key=True)
title = models.TextField()
description = models.TextField()
dueTo = models.DateTimeField()
created = models.DateTimeField()
updated = models.DateTimeField()
priority = models.TextField(choices=Priority.choices)
category = models.TextField(choices=Category.choices)
status = models.TextField(choices=TaskStatus.choices)
contacts = models.ManyToManyField(Contact, default=None, related_name='tasks')
serializers.py
class TaskSerializer(serializers.HyperlinkedModelSerializer):
contacts = ContactSerializer(many=True)
subtasks = SubtaskSerializer(many=True)
class Meta:
model = Task
fields = ['id', 'title', 'description', 'dueTo', 'created', 'updated', 'priority', 'category', 'status',
'subtasks', 'contacts']
What is the best practice to handle this kind of scenario in Django Rest Framework?