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) )?
source share