Django: Add record to the database table if it is not present already

I am learning Django Rest Framework. I have been working on a small project where I am working on 4 models(database tables). The models are 1. Game 2. GameCategory 3. Player 4. PlayerScore.

The table Game is having 5 columns in which category is the foreign key which links the tables Game and GameCategory. Below is the JSON payload for the API.

"url": "http://127.0.0.1:8000/games/3/",
"category": "Shooting",
"name": "PUB G",
"release_date": "2016-11-29",
"played": true

The table GameCategory has one column name.

My current code is in such a way that if I am inserting a record into the table Game with a category which is not present in the table GameCategory I will get the following error message.

"category": [
        "Object with name=ABC does not exist."
    ]

But I want it to be in a way that, when Game data is provided with the value for a category which does not exist in the GameCategory then that category should automatically be added to the GameCategory table,

Sorry if it is a too basic question. I searched everywhere couldn't find the answer and also I am for this framework also to the web development. Thanks in advance.!

Upvotes: 1

Views: 114

Answers (1)

schillingt
schillingt

Reputation: 13731

You can use get_or_create or update_or_create to help handle this scenario.

instance, created = Model.objects.get_or_create(
    foo='bar',
    defaults={'spam': 'eggs'},
)

Upvotes: 1

Related Questions