POST related Fields Django rest Framework
<p>new at django. What I am trying to do is POSTING a model which has a OneToOneField property. How do you POST that?</p>

<p><strong>Models.py</strong></p>

<pre><code>Article(models.Model):
    name=models.CharField(max_length=50)
    description=models.TextField(max_length=200)

Characteristic(models.Model):
   article=models.OneToOneField(Article,on_delete=models.CASCADE,primary_key=True)
   other=models.FloatField()
   another=models.IntegerField()
</code></pre>

<p><strong>Serializer.py</strong></p>

<pre><code>class ArticleSerializer(serializers.ModelSerializer):
    class Meta:
        model=Article
        field='__all__'
class CharacteristicSerializer(serializers.ModelSerializer):
    article=serializers.StringRelatedField()
    class Meta:
        model=Characteristic
        field='__all__'
</code></pre>

<p><strong>Views.py</strong> POST METHOD (API Based)</p>

<pre><code>def  post(self, request,format=None):
    serializer=CharacteristicSerializer(data=request.data)
    if serializer.is_valid():
        serializer.save()
        return Response(serializer.data,status=status.HTTP_201_CREATED)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
</code></pre>

<p>If I try to POST with something like this:</p>

<blockquote>
  <p>(some_url...)/characteristics/ other=4.4 another=4 post=1</p>
</blockquote>

<p>I get the next error:</p>

<blockquote>
  <p>django.db.utils.IntegrityError: (1048, "Column 'post_id' cannot be
  null")</p>
</blockquote>

<p>The idea is to receive the id of the model Article and then save the model Characteristic. </p>

<p>Any ideas?</p>

<p>Finally I was able to solve it. It is only about dictionaries.</p>

<p><strong>Method POST</strong></p>

<pre><code>def  post(self,request,format=None):
    serializer=CharacteristicsSerializer(data=request.data)
    if serializer.is_valid():
        tmp=self.get_article(pk=int(self.request.data['article']))
        serializer.save(article=tmp)
        return Response(serializer.data,status=status.HTTP_201_CREATED)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
</code></pre>

<p>For now that is working, if there is another better way to do it and someone want to share it I'll be thankful </p>

python django django-rest-framework