0👍
Just loop over instance.phonenumber_set.all()
at your update()
method and you will have complete access to those related objects.
for ex:
def update(self, instance, validated_data):
for phonenumber in instance.phonenumber_set.all():
# do what you want with phonenumber, like phonenumber.id
instance
is the current object that is being updated at your serializer and it is being passed as an argument to update()
as you can see, so you can access and do anything with it as you normally do.
Tip:
It’s better to add related_name
to related_contact
to make it better readability, also change related_contact
to contacts
. related_name
is used for selecting reverse relations as we did just like now.
I think it’s better to do so:
contacts = models.ForeignKey(to='ContactModel', on_delete=models.CASCADE, related_name='phonenumbers')
so instead of using phonenumber_set
it will be phonenumbers
for better readability but the name with _map
still valid too, see this answer for more info about related_name
Source:stackexchange.com