Editing the foreign key field in Serializer - Django Rest Framework
<p>I am using Django Rest Framework. I am using this suggestion for adding new value in auto-suggest  <a href="https://stackoverflow.com/questions/14577014/select2-dropdown-but-allow-new-values-by-user/31645758#31645758">Select2 dropdown but allow new values by user?</a> . But it seems almost impossible for me.</p>

<p>Payee is the foreign key field. If string along with '(NEW)' is returned instead of primary key, I need to create the object in the Contacts model and should set primary key of the newly created object to payee field.</p>

<p>models.py</p>

<pre><code>class Contacts(models.Model):
    no = models.AutoField(primary_key=True)
    name = models.CharField(max_length=25)
class Transactions(models.Model):
    payee = models.ForeignKey(Contacts,null=True, related_name = 'transactions_payee')
    reminder = models.ForeignKey(Reminders, related_name='transaction_reminders',blank=True, null=True) 
</code></pre>

<p>serializers.py</p>

<pre><code>class TransactionSerializer(serializers.ModelSerializer):
    reminder = ReminderSerializer()

    class Meta:
      model = Transactions
      fields=('pk','payee','reminder'...)

    def validate_payee(self, value):
      if "  (NEW)" not in value:
        return value
      else:
        payee = value.replace("  (NEW)", "")
        contact = Contacts.objects.create(name = payee)
        value = contact.no
        return value

    def create(self, validated_data):
       ...  #writable nested serializer for reminder field.

    def update(self, instance, validated_data):
       ...  #writable nested serializer for reminder field.
</code></pre>

<p>The validate_payee is not even called. I even tried adding the same logic inside create() but somewhere the django's default validator comes before all of that and throws the error message saying </p>

<pre><code>{payee: ["Incorrect type. Expected pk value, received unicode."]}
</code></pre>

<p>I am a beginner in Django. I have search almost all the stackoverflow questions. Nothing works for me or maybe I am making a mistake somewhere.</p>