我尝试实现python SqlAlchemy对象的批量插入。我还设置了主键为user_label
和book_label
的表。
当我尝试实现插入而不在类对象上调用主键表设置时,
我遇到了这个错误:
{"error":{"name":"UnexpectedError","code":10000,"message":"(psycopg2.errors.NotNullViolation) null value in column \"id\" violates not-null constraint\nDETAIL: Failing row contains (null, user02, AKA6, t, 2019-06-04 00:00:00+00, 2019-06-11 00:00:00+00).\n\n[SQL: INSERT INTO user_fav_books (user_label, book_label, is_free_assigned, free_assign_date, free_assign_end_date) VALUES (%(user_label)s, %(book_label)s, %(is_free_assigned)s, %(free_assign_date)s, %(free_assign_end_date)s)]\n[parameters: ({'book_label': 'AKA6', 'user_label': 'user02', 'free_assign_date': datetime.date(2019, 6, 4), 'free_assign_end_date': datetime.date(2019, 6, 11), 'is_free_assigned': True}, {'book_label': 'AKS6', 'user_label': 'user02', 'free_assign_date': datetime.date(2019, 6, 18), 'free_assign_end_date': datetime.date(2019, 6, 25), 'is_free_assigned': True}, {'book_label': 'AK46', 'user_label': 'user02', 'free_assign_date': datetime.date(2019, 7, 2), 'free_assign_end_date
请告诉我:如何使用自定义主键设置来设置类对象?
这是我的工作准则:
class UserFavBooks(Base):
__tablename__ = 'user_fav_books'
user_label = Column(String)
book_label = Column(String)
is_free_assigned = Column(Boolean , default=True)
free_assign_date = Column(DateTime(timezone=True), default=func.now())
free_assign_end_date = Column(DateTime(timezone=True), default=func.now())
session = sessionmaker(bind=engine)()
session.connection()
session.add_all(
[
UserFavBooks(
user_label="user02",
book_label="AKA6",
is_free_assigned=True,
free_assign_date= DT.date.today() + DT.timedelta(days=7*0),
free_assign_end_date= DT.date.today() + DT.timedelta(days=7*1)
),
UserFavBooks(
user_label="user02",
book_label="AKS6",
is_free_assigned=True,
free_assign_date= DT.date.today() + DT.timedelta(days=7*2),
free_assign_end_date= DT.date.today() + DT.timedelta(days=7*3)
),
UserFavBooks(
user_label="user02",
book_label="AK46",
is_free_assigned=True,
free_assign_date= DT.date.today() + DT.timedelta(days=7*4),
free_assign_end_date= DT.date.today() + DT.timedelta(days=7*5)
),
UserFavBooks(
user_label="user02",
book_label="AK26",
is_free_assigned=True,
free_assign_date= DT.date.today() + DT.timedelta(days=7*6),
free_assign_end_date= DT.date.today() + DT.timedelta(days=7*7)
)
]
)
session.commit()
return 'Hello World!'
如果我在类对象中替换了这些参数,
user_label = Column(String , primary_key=True)
book_label = Column(String , primary_key=True)
它给出了:
违反了非null id约束。在数据库表设计中,我根本没有id
。错误消息告诉我,我必须插入id,这对于插入新数据完全没有意义。
{"error":{"name":"UnexpectedError","code":10000,"message":"(psycopg2.errors.NotNullViolation) null value in column \"id\" violates not-null constraint\nDETAIL: Failing row contains (null, user02, AKA6, t, 2019-06-04 00:00:00+00, 2019-06-11 00:00:00+00).\n\n[SQL: INSERT INTO user_fav_books (user_label, book_label, is_free_assigned, free_assign_date, free_assign_end_date) VALUES (%(user_label)s, %(book
这是我的数据库表设计: