Home > Blockchain >  How to send JSON format data in postman to django models that have a foreign key to another model?
How to send JSON format data in postman to django models that have a foreign key to another model?

Time:05-14

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."
    ]
}

CodePudding user response:

you are referencing non existing id. if you use foreign key in Django it references the primary key of the referenced model so the solution is

step 1: get the article with postman
step 2: copy one of the id of the article
step 3: paste the id to articleId
{
    "userId":"153344",
    "location":"Ethiopia",
    "eventType":"1",
    "articleId":"here",
    "communityId":"1234567",
    "source":"1",
    "timestamp":"123456"
    
}

CodePudding user response:

You are getting this error because the articleId you submitted does not exist. If there is an article with an articleId value you sent, you will not get an error. Before the data you sent is saved, it is checked to see if there is an article with an articleId value. You cannot link to an object that does not exist.

  • Related