Reputation: 11
Here are my models:
class Modules(models.Model):
module_name = models.CharField(max_length=50)
module_duration = models.IntegerField()
class_room = models.IntegerField()
def __str__(self):
return self.module_name
class Students(models.Model):
name = models.CharField(max_length=50)
age = models.IntegerField()
grade = models.IntegerField()
modules = models.ManyToManyField(Modules)
def __str__(self):
return self.name
Here are my views:
class StudentsViewSet(viewsets.ModelViewSet):
serializer_class = StudentsSerializer
def get_queryset(self):
student = Students.objects.all()
return student
def create(self,request,*args, **kwargs):
data = request.data
new_student = Students.objects.create(name=data["name"], age=data['age'], grade=data["grade"])
new_student.save()
for module in data["modules"]:
module_obj = Modules.objects.get(module_name=module["module_name"])
new_student.modules.add(module_obj)
serializer = StudentsSerializer(new_student)
return Response(serializer.data)
class ModulesViewSet(viewsets.ModelViewSet):
serializer_class = ModudesSerializer
def get_queryset(self):
module = Modules.objects.all()
return module ```
When I post this:
*{
"name": "steve",
"age": 16,
"grade": 10,
"modules": [
{
"module_name": "math"
},
{
"module_name": "physics"
}
]
}*
It says:
MultipleObjectsReturned at /app_Five/student/
get() returned more than one Modules -- it returned 2!
I understand that get()
only gets one element. But I think in thefor
loop above, only one module_name
exists for each loop. So each time the get()
executes, there's only one result for it to get. Can anyone tell me what I did wrong there?
Upvotes: 0
Views: 79
Reputation: 176
It seems that you expect the module name to be unique. You probably have multiple Modules
entries in the database with the same module_name
.
To ensure unique names when creating Module entries you could change the Modules model to enforce this:
class Modules(models.Model):
module_name = models.CharField(unique=True, max_length=50)
module_duration = models.IntegerField()
...
Upvotes: 1