0

new at django. What I am trying to do is POSTING a model which has a OneToOneField property. How do you POST that?

Models.py

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()

Serializer.py

class ArticleSerializer(serializers.ModelSerializer):
    class Meta:
        model=Article
        field='__all__'
class CharacteristicSerializer(serializers.ModelSerializer):
    article=serializers.StringRelatedField()
    class Meta:
        model=Characteristic
        field='__all__'

Views.py POST METHOD (API Based)

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)

If I try to POST with something like this:

(some_url...)/characteristics/ other=4.4 another=4 post=1

I get the next error:

django.db.utils.IntegrityError: (1048, "Column 'post_id' cannot be null")

The idea is to receive the id of the model Article and then save the model Characteristic.

Any ideas?

hhc
  • 1
  • 3
  • Not a django person - waitress is what I use ... don't you just need a body for the POST containing the id of the Characteristic instance with key "article", a float with the key "other" and an int with the field "another"? – Neil Gatenby Sep 26 '16 at 19:47
  • 1
    You need to provide POST data in request, not url. – vishes_shell Sep 26 '16 at 19:56
  • I have found this in another post, but you have to give it the data of the other model and my question is to only give the ID of model ARTICLE http://stackoverflow.com/questions/27365486/how-to-post-to-a-django-rest-framework-api-with-related-models – hhc Sep 27 '16 at 05:01

1 Answers1

0

Finally I was able to solve it. It is only about dictionaries.

Method POST

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)

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

hhc
  • 1
  • 3