Skip to content
Advertisement

How to use get_or_create? Error: get() returned more than one Patient — it returned 7

I have a function for fetch API where I create a Django model object for each object in the JSON and store the data in django model. The problem here is everytime I call the route it creates the records again and again, because I use create method, but I made an research that the best way to stop that is to use get_or_create. So, I tried this method but it looks like I missed something, because I got an error: feedback.models.Patient.MultipleObjectsReturned: get() returned more than one Patient — it returned 7!

this is my code before I have 2 for loops so I can loop through every patient and then through every role and save patient with a role:

JavaScript

this is when I tried to use get_or_create method:

JavaScript

this is my models.py:

JavaScript

The Traceback error:

JavaScript

I read the official documentation but there are a some misunderstanding that are not very clear to me about get_or_create method for example I want to check the users only by their email, because I read that it should be something “unique”, so get_or_create checks every field in my model or..? I hope my question is clear if it’s not please let me know

Advertisement

Answer

There simply are multiple objects with the same (first_name, last_name, email, coreapi_id), and get_or_create refuses to do anything since it’s likely a logic problem.

The same would happen with just .get() (which is indeed what .get_or_create() does).

If you mean to e.g. only get the Patient using the coreapi_id field, but if no Patient with that data exists, create them using the other fields, you’ll want to use the defaults argument:

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement