django rest framework nested fields with multiple models


Momokjaaaaa

This is django and django rest framework. I have 2 models: User and Phone.

first question:

I want to be able to update user data (email) as well as phone data (phone number) in 1 api update response. Phone numbers can be 0 or many. Well, it's actually like partial = True. If the user just wants to update the phone number then don't update the email and vice versa.


Additional Information: Phone is not included when registering. Just basic user information (last name, first name, email, password). After registration, the phone can only be updated in the user profile form. The user profile form is actually linked to multiple models i.e. "User and Phone"

second question:

How to serialize multiple phone_numbers and save to db?

class User(AbstractBaseUser):
    email = models.EmailField(unique=True, default='')
    USERNAME_FIELD = 'email'


class Phone(models.Model):
    phone_number = models.CharField(max_length=10)
    owner = models.ForeignKey(User)

--------------------------------------
class UserSerializer(serializers.ModelSerializer):
    phone_number = PhoneSerializer(required=False, many=True)

    class Meta:
        model = User
        fields = ('email, 'phone_number')


class PhoneSerializer(serializers.ModelSerializer):

     class Meta:
          Model = Phone
          fields = ('phone_number')

The phone number field of the html form will have a plus sign to indicate that new phone numbers can be added. example is here

email : [email protected]
phone number: 23423432423
(add more)
phone number: 3423423423
(add more)
...

expected json

{
'email': '[email protected]',
'phone_number': '32432433223234'
}

or if many phone numbers are added

{
'email': '[email protected]',
'phone_number': '32432433223234',
'phone_number': '324342322342323'
}

perhaps

{
'email': '[email protected]',
'phone_number': ['32432433223234','324342322342323']
}

perhaps

{
'email': '[email protected]',
'Phone': [{'id': 1, 'phone_number': '32432433223234'}, {'id': 2, 'phone_number': '324342322342323'}]
}

Can this json be done? How does serializer and modelviewset do this? sorry i'm new to drf

yeast
  1. The default version for any nested objects.

You need to add serializer createand updatemethod:

class UserSerializer(serializers.ModelSerializer):
    phones = PhoneSerializer(required=False, many=True)

    class Meta:
        model = User
        fields = ('email', 'phone_number')

    def create(self, validated_data):
        phones_data = validated_data.pop('phones', [])
        user = super(UserSerializer, self).create(validated_data)
        for phone_data in phones_data:
            user.phone_set.create(phone_number=phone_data['phone_number'])
        return user

    def update(self, instance, validated_data):
        phones_data = validated_data.pop('phones', [])
        user = super(UserSerializer, self).update(instance, validated_data)
        # delete old
        user.phone_set.exclude(phone__in=[p['phone_number'] for p in phones_data]).delete()
        # create new
        for phone_data in phones_data:
            user.phone_set.get_or_create(phone_number=phone_data['phone_number'])
        return user

Application Creation:

{"email": "[email protected]" "phones": [{"phone_number": 12}, {"phone_number": 123}]}

Request an update:

{"phones": [{"phone_number": 22}]}
  1. Optimization of the current structure:

renew

  1. phones_data = validated_data.pop('phones')-> phones_data = validated_data.pop('phones', []), to handle the case of a call without a request.

  2. Should phone update and creation be done in modelviewset?

    No, the serializer is responsible for the conversion native data -> internal objects. So if phone data is received, the PhoneNumberobject should be created.

Related


django rest framework nested fields with multiple models

Momokjaaaaa This is django and django rest framework. I have 2 models: User and Phone. first question: I want to be able to update user data (email) as well as phone data (phone number) in 1 api update response. Phone numbers can be 0 or many. Well, it's actua

django rest framework nested fields with multiple models

Momokjaaaaa This is django and django rest framework. I have 2 models: User and Phone. first question: I want to be able to update user data (email) as well as phone data (phone number) in 1 api update response. Phone numbers can be 0 or many. Well, it's actua

django rest framework nested fields with multiple models

Momokjaaaaa This is django and django rest framework. I have 2 models: User and Phone. first question: I want to be able to update user data (email) as well as phone data (phone number) in 1 api update response. Phone numbers can be 0 or many. Well, it's actua

django rest framework nested fields with multiple models

Momokjaaaaa This is django and django rest framework. I have 2 models: User and Phone. first question: I want to be able to update user data (email) as well as phone data (phone number) in 1 api update response. Phone numbers can be 0 or many. Well, it's actua

Django rest framework. Returns nested multiple models

tomoc4 I'm trying to create a combined viewset that displays data in a nested format of three nested models. I got an error when trying to return to the viewset. Got AttributeError when attempting to get a value for field `runner` on serializer `CombinedSerial

Django rest framework. Returns nested multiple models

tomoc4 I'm trying to create a combined viewset that displays data in a nested format of three nested models. I got an error when trying to return to the viewset. Got AttributeError when attempting to get a value for field `runner` on serializer `CombinedSerial

Django rest framework. Returns nested multiple models

tomoc4 I'm trying to create a combined viewset that displays data in a nested format of three nested models. I got an error when trying to return to the viewset. Got AttributeError when attempting to get a value for field `runner` on serializer `CombinedSerial

Django rest framework. Returns nested multiple models

tomoc4 I'm trying to create a combined viewset that displays data in a nested format of three nested models. I got an error when trying to return to the viewset. Got AttributeError when attempting to get a value for field `runner` on serializer `CombinedSerial

Django rest framework. Returns nested multiple models

tomoc4 I'm trying to create a combined viewset that displays data in a nested format of three nested models. I got an error when trying to return to the viewset. Got AttributeError when attempting to get a value for field `runner` on serializer `CombinedSerial

Multiple models in Django Rest Framework?

Coderaemon: I am using Django Rest Framework . I want to serialize multiple models and send as response. Currently, only one model can be sent per view (as CartViewshown below, only Cart objects are sent). The following models (unrelated) can be there. class S

Multiple models in Django Rest Framework?

Coderaemon: I am using Django Rest Framework . I want to serialize multiple models and send as response. Currently, only one model can be sent per view (as CartViewshown below, only Cart objects are sent). The following models (unrelated) can be there. class S

Multiple models in Django Rest Framework?

Coderaemon I am using Django Rest Framework . I want to serialize multiple models and send as response. Currently I can only send one model per view (as CartViewbelow, only the Cart object). The following models (unrelated) can be there. class Ship_address(mod

Multiple models in Django Rest Framework?

Coderaemon: I am using Django Rest Framework . I want to serialize multiple models and send as response. Currently, only one model can be sent per view (as CartViewshown below, only Cart objects are sent). The following models (unrelated) can be there. class S

Nested serializers "through models" in Django Rest Framework

bdex I'm having trouble serializing an intermediate "pivot" model and attaching it to each item in a "many-to-many" relationship in Django Rest Framework. example: models.py: class Member(models.Model): name = models.CharField(max_length = 20) groups =

Nested serializers "through models" in Django Rest Framework

bdex I'm having trouble serializing an intermediate "pivot" model and attaching it to each item in a "many-to-many" relationship in Django Rest Framework. example: models.py: class Member(models.Model): name = models.CharField(max_length = 20) groups =

Nested serializers "through models" in Django Rest Framework

bdex I'm having trouble serializing an intermediate "pivot" model and attaching it to each item in a "many-to-many" relationship in Django Rest Framework. example: models.py: class Member(models.Model): name = models.CharField(max_length = 20) groups =

Nested annotation fields in Django REST Framework serializer

Robin I'm trying to view nested annotated (aggregated/calculated) fields in a Django REST Framework serializer. This allows for cleaner handling of annotated fields. This post is similar to Aggregate (and other annotated) fields in Django Rest Framework serial

Django Rest Framework - how to serialize nested fields

SolidCoder I have one that returns all associated objects CustomerSerializerusing a reverse foreign key field .imagesImage class CustomerSerializer(serializers.ModelSerializer): class Meta: model = Customer fields = ('id', 'name', 'images'

Nested annotation fields in Django REST Framework serializer

Robin I'm trying to view nested annotated (aggregated/calculated) fields in a Django REST Framework serializer. This allows for cleaner handling of annotated fields. This post is similar to Aggregate (and other annotated) fields in Django Rest Framework serial

Django Rest Framework - how to serialize nested fields

SolidCoder I have one that returns all associated objects CustomerSerializerusing a reverse foreign key field .imagesImage class CustomerSerializer(serializers.ModelSerializer): class Meta: model = Customer fields = ('id', 'name', 'images'

Nested serializer fields Django Rest Framework

Isaac Hattilima I have two models (user and province) and serializer. The user creates a province and in the province model I have the user id. The challenge is when creating the nested serializer, I only want the user's first_name and last_name, but it gives