Issue
I have tried to send a POST request to django views.py
file using postman.
It was working when I sent a POST and GET request to django models that haven't ForeignKey field. However, when I tried to send a POST request to a django model that have a ForeignKey field, it wasn't working. My question is how to send a JSON format data using postman to django models that have a Foregin Key field.
The models are as follows:
class Article(models.Model):
authorId=models.CharField(max_length=100)
authorResidence=models.CharField(max_length=100)
communtId=models.CharField(max_length=100)
content=models.TextField()
contentId=models.CharField(max_length=100)
source=models.CharField(max_length=100)
timestamp=models.IntegerField()
title=models.CharField(max_length=100)
class Interactions(models.Model):
userId=models.CharField(max_length=100,unique=True)
location=models.CharField(max_length=100)
eventType=models.IntegerField(unique=True)
articleId=models.ForeignKey(Article,on_delete=models.CASCADE)
communityId=models.CharField(max_length=100)
source=models.IntegerField()
timestamp=models.IntegerField()
I have tried in this way (in postman):
{
"userId":"153344",
"location":"Ethiopia",
"eventType":"1",
"articleId":"67353536",
"communityId":"1234567",
"source":"1",
"timestamp":"123456"
}
As you can see the articleId is a foreignKey field. Here is the output:
{
"articleId": [
"Invalid pk \"67353536\" - object does not exist."
]
}
Solution
Django models have id field by default so the primary key of the models will be the id. if you use foreign key in Django model, it references the primary key of the referenced model. Here what you face is, you are referencing non existing id - meaning wrong id, or, no instance of article exist with that id.
step 1: get all the articles with postman
step 2: copy one of the id's of the articles
step 3: paste that id to articleId like shown below, if id is 2 then you should right like this
{
"userId":"153344",
"location":"Ethiopia",
"eventType":"1",
"articleId":"2",
"communityId":"1234567",
"source":"1",
"timestamp":"123456"
}
Answered By - Samuel Abatneh
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.