最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin2浏览0评论

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.

发布评论

评论列表(0)

  1. 暂无评论