title: Django Rest ModelSerializer Find or Create Pattern
body: <p>I am new to Django. Reading a lot of ways to do the same thing--but not finding the proverbial needle in a haystack. One such needle is a simple "Find or Create" pattern for Django Rest.</p>
  
  <p>I am trying to find a simple example of how to go about implementing a find or create pattern for one of my model data using Django Rest ModelSerializer and CreateAPIView methods. Let say that I have a model Location with a unique field 'address'. I want to return an existing instance when the address already exists on my database. If the address does not exist, I want to create an entry in the database and populate other computed values for the object.</p>
  
  <pre><code>class Location(models.Model):
      address = models.CharField(max_length=100, unique=True,)
      thing1 = models.CharField(max_length=100, blank=True, null=True, )
      thing2 = models.CharField(max_length=100, blank=True, null=True, )
  
      def compute_things(self, address):
          somevalue1 = ...
          somevalue2 = ....
          return somevalue1, somevalue2
  </code></pre>
  
  <p>Now, I am not exactly sure how to write the serializer and view so that:</p>
  
  <ol>
  <li>A new location is created and returned with all the fields
  initialized when a new address is seen for the first time</li>
  <li>An existing location that matches 'address' in the database is
  returned in lieu of step 1</li>
  </ol>
  
  <p>What else should I define for the model? How do I write APIView and CreateSerializer to get the right thing? Where should I call the compute_thing() in order to populate the missing fields.</p>
  
  <p>For the serializer:</p>
  
  <pre><code>class LocationCreateSerializer(ModelSerializer):
      class Meta:
          model = Location
  </code></pre>
  
  <p>And for the APIView:</p>
  
  <pre><code>class LocationCreateAPIView(CreateAPIView):
      serializer_class = LocationCreateSerializer
      queryset = Location.objects.all()
  </code></pre>
  
  <p>The APIView and Serializer above are not enough for what I need. What else do I need to add to model, View and Serializer to get that behavior that I am seeking? </p>
  
  <p>I don't want the View nor the Serializer to return validation errors for duplicate 'addresses'--just the existing instance and not an error. It looks like restore_object() is deprecated. Is there a way to accomplish what I am seeking?</p>