I'm writing a contacts service in Django-REST-Framework.
I have a Contact
Model and a PhoneNumber
Model which has a foreignKey field that shows which contact does it belong to.
Here are my models:
class ContactModel(models.Model):
firstname = models.CharField(max_length=50, blank=False)
lastname = models.CharField(max_length=50, blank=False)
class PhoneNumber(BaseModel):
country_code = models.CharField(max_length=VERY_SHORT_STRING_SIZE, blank=False)
phone_number = models.CharField(max_length=SHORT_STRING_SIZE, blank=False, null=False)
label = models.CharField(max_length=NORMAL_STRING_SIZE, blank=True, default='')
related_contact = models.ForeignKey(to='ContactModel', on_delete=models.CASCADE)
I want to make a CRUD
api for my Contacts. I have a ModelViewSet
and a ModelSerializer
for that. serializer codes is as follows:
class ContactSerializer(serializers.ModelSerializer):
phonenumber_set = PhoneSerializer(many=True, required=False)
class Meta:
model = ContactModel
fields = '__all__'
class PhoneSerializer(serializers.ModelSerializer):
class Meta:
model = PhoneNumber
fields = ['id', 'country_code', 'phone_number', 'label']
As it's been specified here I should override update and create methods in order to update and create PhoneNumbers of my Contact.
The problem is that if I override those functions I have to use them like this:
class ContactSerializer(serializers.ModelSerializer):
...
def create(self, validated_data):
# some code for creating both PhoneNumber and Contact
def update(self, instance, validated_data):
# some code for updating both PhoneNumber and Contact
and unfortunately, 'validated_data' argument doesn't bring the 'id' of my PhoneNumber objects, because 'id' fields are AutoFields and AutoFields will be read_only in DRF (it's explained Here).
Is there a way for me to have access to my 'id' field in my update method? (kinda need it badly)
Thanks.