Reusing an Existing Object in Django Rest Framework Nested Serializer

How to switch to reusing a reference object when using nested serializers in a drf file:

Let's say I have the following two Model s:

 class Address(models.Model): address_line = models.CharField(max_length=45) class Person(models.Model): name = models.CharField(max_length=45) address = models.ForeignKey(Address) 

with Serializer s:

 class AddressSerializer(serializers.ModelSerializer): class Meta: model = Address class PersonSerializer(serializers.ModelSerializer): address = AddressSerializer() class Meta: model = Person 

Serializers now process both Address and Person together. For example, when I post the following:

 { 'name': 'Alex', 'address': { 'address_line': "1 Here" } } 
Is being created

a Person , and Address is created using Person , which points to the newly created Address .

What is the best way to NOT create a new Address , but reuse an existing Address if there is already an Address with the given address_line ? If I would like to make the address_line unique field? (reusing this object is sometimes called "interning")

What about having two address fields address_line1 and address_line2 , and I wanted to reuse the Address object if an Address already exists with both of these fields (i.e. unique_together=(address_line1, address_line2) )?

+5
source share
1 answer

I recently ran into a similar problem, solving it using the following approach (the code has not been tested, its just for reference):

 class PersonSerializer(serializers.ModelSerializer): address = AddressSerializer() class Meta: model = Person def create(self, validated_data): # pop the validated user data # assuming its a required field, # it will always be there in validated_data address = validated_data.pop('address') try: address = Address.objects.get(address_line=address.get('address_line')) except ObjectDoesNotExist: address_serializer = AddressSerializer(data=address) address_serializer.is_valid(raise_exception=True) address = address_serializer.save() else: # save the user and update the validated_data for setting up profile validated_data['address'] = address return super(PersonSerializer, self).create(validated_data) 

Hope this helps :)

0
source

Source: https://habr.com/ru/post/1204224/


All Articles