Django Rest Framework API #22 / Many To Many Relationship , Nested Data
ฝัง
- เผยแพร่เมื่อ 24 ส.ค. 2024
- Django Rest Framework API Model Relationships
How to implement ManyToMany Relationship to link multiple objects of one model with multiple objects of another.?
How to get data for nested fields?
How to create nested field data using nested serializer?
How to override create method to handle the nested data represented by the ManyToMany relationship.
🎧 Music : • Study music | Programm...
Music Channel : @tuningthecode
Source Code: github.com/Cod...
Many To One relationship Video:
• Django Rest Framework ...
One To One relationship Video:
• Django Rest Framework ...
thanks a lot!!!!! u help me a lot man thanks thanks !!!!
It saved my life bro, well done, Great Job
This approach works, but it also overrides all of the validations provided by the serializer class, which could lead to problems down the road. I used this video as a stepping stone, then moved it to the create() method in the serializer class:
class StudentsSerializer(serializers.ModelSerializer):
class Meta:
model = Students
fields = ['id', 'name', 'age', 'grade', 'modules']
depth = 1
def create(self, validated_data):
module_data = validated_data.pop('modules', [])
new_student = Student.objects.create(**validated_data)
for module in module_data:
module_obj = Modules.objects.get(module_name=module["module_name"])
new_student.modules.add(module_obj)
return new_student
hi, but did you keep the create method in the view too? if i override only the serializer method it doesn't work.. thanks
@@robyguglie no I removed the create method from the view. Try making this mod to ModuleSerializer:
class ModuleSerializer(serializers.ModelSerializer):
id = IntegerField(label='ID')
by default, id is set to read_only=True, so it needs to be overridden or it won't be added to your validated_data in StudentSerializer.
so it seems like you combined the Student viewset and the Student serializer essentially?
also can anyone explain what validations are being overridden and whats so bad about it?
Hi thanks for this, would it be possible to send not a list of objects but just a list of module ids (like [1,2,3]) in the post body.
Thank you very much helped alot❤
Thank you so much man ❤️
This is exactly what I needed.
I’m glad I could help
Waoo, thanks very very much! This is my solutions in apiRest parents child or main and detail! Nice!
Thanks!
Great, thanks for the well explained video 👍🏻
Thank you
Great tutorial. Thanks for sharing!
Thanks, really informative👍🏽👍🏽
Aashay Amballi thank you
How add filters for ManyToMany. Like filtering list of students took physics.
Thanks a lot for this video!!!
10x! your example helped me :)
Thank you very mucho. CLCL
Really helpful bro thanks
Glad it helped
Excelent material thank you very much! But the audio its kind of bad too much mouth noises
Thank you for the support and feedback, will keep that in mind ✌🏻
Is it something I do not understand, or do you create an object bypassing the serializer, and use it only for parsing in JSON? It seems to be a mistake to save data without validation.
Hello Gosha, it’s a different approach, plus you can do data validation on the serializer level or view level. This tutorial doesn’t tackle data validation though.
manyToMany relation is symetrical. What if you also want to display the list of students in a modul record ?
You can add M-M field in its model
I was wondering what do we need to do if we wanted to create a new student with a completely new module that doesn't exist.
Hello Viktor, you can create the new module object then create the new student object and assign the module to it inside the student view.
Muito obrigado! :)
De nada 👍🏻
Hello; sameone help me please
views.py", line 23, in create
module_obj = Modules.objects.get(module_name=module["module_name"])
TypeError: string indices must be integers
I have a similar requirement. Where I wanted to update many to many field which is blank when we create it. In this case like when we create a Student, modules should blank. Can you please let me know how can I achieve it ?
I have searched a lot but not found any relevant answer .
Please help.
Thanks.
Please email me at:
Codes.environment@gmail.com
And I’ll help you with it.
Thanks bro
Thank you .. very Nice.. how about for update Many 2 Many, example for update Students Modules ?
But this way will by pass serializers.is_valid ?
Thank you Nabila, for the update you need to override the update method inside your view. Please see this tutorial, it’ll help you understand the concept:
th-cam.com/video/r0Y_Qp21liI/w-d-xo.html
In this tutorial we are using the serializer to serializer the data only, you can choose to validate your data in the view as well.
nice video
how do you add and remove modules to and from students that already exist????
Oh I see it is in the NEXT tutorial. Watching that one next. Thanks for this.
How we can override for update /PUT method. If some modules are added or deleted from the students..then how to do that?
Please help sir. I even emailed u for this 🙏
Please see this tutorial for UPDATE / PUT methods:
th-cam.com/video/f2xky4CwQ9Q/w-d-xo.html
@@codeenvironment for many to many fields I m facing problem..how to do for many to many fields?
Love this. BTW can I ask how to implement a custom permission to this?
For example the app you are trying to do has Author and Book model. Can you teach me how to create custom permission where only the authors of the book can modify the book.
Thanks Jonathan,
I think the best way to achieve that is by comparing the logged in user with the book's author, and if the result is True then you can perform the changes.
Hello, would the logic be the same for functional views? not class based views
The logic is the same but with the functional views extra work is required
could you please show the post request for create method using form-data?
Do you mean using form-data with post man?
@@codeenvironment yes, nested form-data with file actually.
{
"title": "x",
"details": "y",
"images": [
{
"image": file,
" caption": caption
}, { another image}
]
}
Love this video !!
One question , is there a way to select the modules in code? and not in django admin
Thank you 😊, yes of course, you just need their IDs to get the models then add them.
will it also work if we post the data using form data in postman ? if yes then how we can define its key there?? please tell
You can’t send a nested object using form data
@@codeenvironment Actually I am unable to send this data from Android side , I have posted this data by writing the key multiple times in the postman but Android team is saying we can't write keys multiple times our side then I have tried :-
['key1','key2'......] Etc but still not working please help me
And one more thing is that
If I directly assign this keys like .add('key1','key2',....)
Then it is working perfectly
Brother I found it's solution I just iterate over the incoming list and remove the special symbols and finally I made a new list and then saved it 😍😍😍
@@mohitrathore8808 well done 👍🏻
@@codeenvironment thanks bro😋
I have a question, what should be done to view all students linked to a module?
Many to Many with serializer how to get same method?
Hi, do you think you could expand on that video with custom 'Through' models in Many2many relationships? I have an issue with something i'm trying to build:
```
modifiers = models.ManyToManyField(Modifier, through='ItemModifier', related_name='items')
```
Once put through a serializer, it returns the serialized item for Modifier instead of ItemModifier, which is supposed to have extra fields
Please email me at:
Codes.environment@gmail.com
And I’ll help you
Server Error (500)