简体   繁体   中英

POST related Fields Django rest Framework

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM