'How to make a post call with Django where your models are many to many?
I am trying to understand how I should be structuring my post call when I want to do a many to many relationship.
class School(models.Model):
name = models.CharField(unique=True, max_length=30, blank=True)
teachersAtSchool = models.ManyToManyField('Teacher', blank=True)
class Teacher(models.Model):
account = models.ForeignKey(Account, default=1, on_delete=models.SET_DEFAULT)
schoolsTeachingAt = models.ManyToManyField('School', blank=True)
I send in the following JSON:
{
"name": "school Name",
"teachersAtSchool": 0
}
and get the following result:
{
"id": 13,
"name": "school Name",
"teachersAtSchool": []
}
Edit: Showing serialize
class SchoolModelSerializer (serializers.ModelSerializer):
class Meta():
model = models.School
fields = '__all__'
depth = 1
class TeacherModelSerializer (serializers.ModelSerializer):
class Meta():
model = models.Teacher
fields = '__all__'
depth = 1
I have checked there are indeed teachers in the database that I can get with my GET call. I even tried with different id's but I get the same result. Its possible this is something super simple I just don't understand. Please help me.
Regards
Solution 1:[1]
@simple_code said: "I don't think you need depth=1. As ModelSerializers do primary keys by default. – simple_code"
This resulted in it defaulting back to id which was the solution.
I found this answer out by following their suggestion "Also try and play with the serializer by itself because the json input it expects is the same as the json output it creates. So if you have a valid school with teachers, print what the serializer would output. That should give you valid input for the serializer. - simple_code" and noticing the json I received back was the whole serialized class.
Thank you everyone for you help and suggestions. I hope this post helps anyone.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | CloudyGoat |
