最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

postgresql - How to insert String data as enum into Postgres database in Python - Stack Overflow

matteradmin7PV0评论

I'm trying to add a String type data into a postgresql database in Python by Prisma. The culumn in database is defined as a specific enum type in Prisma schema. I tried to insert by a String mapping. However the insert was failed with not support with String type. What should I do?

from enum import Enum
from prisma import Prisma

db = Prisma()
os.environ['DATABASE_URL'] = ''
db.connect()

class DifficultyLevel(Enum):
    EASY = 'EASY'
    MEDIUM = 'MEDIUM'
    HARD = 'HARD'
    LUCK = 'LUCK'

def map_question_difficulty(generated_difficulty):
    difficulty_mapping = {
        'Easy': DifficultyLevel.EASY,
        'Medium': DifficultyLevel.MEDIUM,
        'Hard': DifficultyLevel.HARD,
        'LUCK': DifficultyLevel.LUCK
    }
    return difficulty_mapping.get(generated_difficulty, DifficultyLevel.EASY).value  # Default to EASY if difficulty not found

async def insert_questions_to_db(questions):
    try:
        for question in questions:
            db.elementgenerated.create(
                data={
                    "difficulty": map_question_difficulty(question['difficulty'])
                }
            )
        logging.info(f"Successfully inserted {len(questions)} questions into the database.")
    except Exception as e:
        logging.error(f"Error inserting questions into the database: {e}")
        raise

Definition in Prisma schema:

enum DifficultyLevel {
  EASY
  MEDIUM
  HARD
}

Here the Program gave feedback with: 'prisma.errors.DataError: Error converting field "difficulty" of expected non-nullable type "String", found incompatible value of "EASY".' The question['difficulty'] is a String object like 'Easy', 'Medium' or 'Hard'.

I'm trying to add a String type data into a postgresql database in Python by Prisma. The culumn in database is defined as a specific enum type in Prisma schema. I tried to insert by a String mapping. However the insert was failed with not support with String type. What should I do?

from enum import Enum
from prisma import Prisma

db = Prisma()
os.environ['DATABASE_URL'] = ''
db.connect()

class DifficultyLevel(Enum):
    EASY = 'EASY'
    MEDIUM = 'MEDIUM'
    HARD = 'HARD'
    LUCK = 'LUCK'

def map_question_difficulty(generated_difficulty):
    difficulty_mapping = {
        'Easy': DifficultyLevel.EASY,
        'Medium': DifficultyLevel.MEDIUM,
        'Hard': DifficultyLevel.HARD,
        'LUCK': DifficultyLevel.LUCK
    }
    return difficulty_mapping.get(generated_difficulty, DifficultyLevel.EASY).value  # Default to EASY if difficulty not found

async def insert_questions_to_db(questions):
    try:
        for question in questions:
            db.elementgenerated.create(
                data={
                    "difficulty": map_question_difficulty(question['difficulty'])
                }
            )
        logging.info(f"Successfully inserted {len(questions)} questions into the database.")
    except Exception as e:
        logging.error(f"Error inserting questions into the database: {e}")
        raise

Definition in Prisma schema:

enum DifficultyLevel {
  EASY
  MEDIUM
  HARD
}

Here the Program gave feedback with: 'prisma.errors.DataError: Error converting field "difficulty" of expected non-nullable type "String", found incompatible value of "EASY".' The question['difficulty'] is a String object like 'Easy', 'Medium' or 'Hard'.

Share Improve this question asked Nov 15, 2024 at 21:38 Jerry ChenJerry Chen 231 silver badge2 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

missing enumerated value

Your prisma schema should also include LUCK. A discrepancy between python and prisma seems like a Bad Thing.

read the diagnostic

prisma.errors.DataError: Error converting field "difficulty" of expected non-nullable type "String", found incompatible value of "EASY".' The question['difficulty'] is a String object like 'Easy', 'Medium' or 'Hard'.

This suggests revising your Enum class to be:

class DifficultyLevel(Enum):
    EASY = 'Easy'
    MEDIUM = 'Medium'
    HARD = 'Hard'
    LUCK = 'Luck'

auto()

Side note: consider DRYing up the class by defining it this way:

from enum import Enum, auto

class DifficultyLevel(Enum):
    EASY = auto()
    MEDIUM = auto()
    HARD = auto()
    LUCK = auto()

    def __str__(self):
        return self.name.title()

And then use f-string or str() rather than .value.

Post a comment

comment list (0)

  1. No comments so far