POST related Fields Django rest Framework

2019-09-06 01:51发布

问题:

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?

回答1:

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