在sqlalchemy中从关系中获取对象的属性(Get attribute of object from relationship in sqlalchemy)
请考虑以下定义某些类的代码:
from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, Float, String, DateTime from sqlalchemy import ForeignKey, UniqueConstraint from sqlalchemy.orm import relationship, backref class Base(object): id = Column(Integer, primary_key=True) Base = declarative_base(cls=Base) class Teacher(Base): __tablename__ = 'teacher' email = Column(String, unique=True) name = Column(String, nullable=False) password = Column(String) base_score = Column(Float) time_zone = Column(String) def __repr__(self): return '<Teacher({0})>'.format(self.email) class Class(Base): __tablename__ = 'class' teacher_id = Column(Integer, ForeignKey('teacher.id', ondelete="CASCADE"), nullable=False, index=True) Teacher = relationship("Teacher", backref=backref('classes', order_by='Class.id')) name = Column(String, index=True) __table_args__ = (UniqueConstraint('teacher_id','name'),) def __repr__(self): return '<Class({0})>'.format(self.name) class Student(Base): __tablename__ = 'student' class_id = Column(Integer, ForeignKey('class.id', ondelete="CASCADE"), nullable=False, index=True) Class = relationship("Class", backref=backref('students', order_by='Student.id')) name = Column(String, index=True) __table_args__ = (UniqueConstraint('class_id','name'),) def __repr__(self): return '<Student({0})>'.format(self.name)
以下代码使用类:
from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker engine = create_engine('sqlite:///:memory:', echo=True) Base.metadata.create_all(engine) Session = sessionmaker(bind=engine) session = Session() t = Teacher(email='test@example.com',name='Cool Guy',base_score=100,time_zone='America/Chicago') c1 = Class(Teacher=t,name='Mathematics') s1 = Student(Class=c1,name='Bob Roberts')
首先,我想知道是否正确定义c1是正确的方法(使用Teacher参数。)
其次,我知道我是否可以通过以下方式获得学生的老师:
s1.Class.Teacher
但是,无论如何(并且正常)在Student类上直接创建Teacher属性? 我尝试添加:
Teacher = Class.Teacher
在类定义中,但是扔了:
AttributeError: 'RelationshipProperty' object has no attribute 'Teacher'
显然,这不是什么大不了的事,但我想知道正确的方式(如果有一个,或者没有一个),因为我正在努力学习sqlalchemy。
Consider the following code defining some classes:
from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, Float, String, DateTime from sqlalchemy import ForeignKey, UniqueConstraint from sqlalchemy.orm import relationship, backref class Base(object): id = Column(Integer, primary_key=True) Base = declarative_base(cls=Base) class Teacher(Base): __tablename__ = 'teacher' email = Column(String, unique=True) name = Column(String, nullable=False) password = Column(String) base_score = Column(Float) time_zone = Column(String) def __repr__(self): return '<Teacher({0})>'.format(self.email) class Class(Base): __tablename__ = 'class' teacher_id = Column(Integer, ForeignKey('teacher.id', ondelete="CASCADE"), nullable=False, index=True) Teacher = relationship("Teacher", backref=backref('classes', order_by='Class.id')) name = Column(String, index=True) __table_args__ = (UniqueConstraint('teacher_id','name'),) def __repr__(self): return '<Class({0})>'.format(self.name) class Student(Base): __tablename__ = 'student' class_id = Column(Integer, ForeignKey('class.id', ondelete="CASCADE"), nullable=False, index=True) Class = relationship("Class", backref=backref('students', order_by='Student.id')) name = Column(String, index=True) __table_args__ = (UniqueConstraint('class_id','name'),) def __repr__(self): return '<Student({0})>'.format(self.name)
And the following code using the classes:
from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker engine = create_engine('sqlite:///:memory:', echo=True) Base.metadata.create_all(engine) Session = sessionmaker(bind=engine) session = Session() t = Teacher(email='test@example.com',name='Cool Guy',base_score=100,time_zone='America/Chicago') c1 = Class(Teacher=t,name='Mathematics') s1 = Student(Class=c1,name='Bob Roberts')
First of all, I want to know if defining c1 like that is the right way (Using the Teacher argument.)
Second of all, I know if I can get the Teacher of a student by doing:
s1.Class.Teacher
But is there anyway ( and is it normal) to create a Teacher attribute directly on the Student class? I tried adding:
Teacher = Class.Teacher
In the class definition, but that threw:
AttributeError: 'RelationshipProperty' object has no attribute 'Teacher'
Obviously, it's not that big of a deal, but I want to know the correct way (if there is one, or that there is not one) as I'm trying to learn sqlalchemy better.
原文:https://stackoverflow.com/questions/16391768
最满意答案
当date绑定到GridView时,它已经是一个
String
而不再是DateTime
。 我建议你将列的DataFormatString
设置为{0:d}
,它将根据页面UI显示日期。When date is bound to GridView, it is already a
String
and no more aDateTime
. I suggest you set theDataFormatString
of the column to{0:d}
, which will display the date based on the page UI.
相关问答
更多-
尝试这个 DateTime dateTime = new DateTime(); dateTime = Convert.ToDateTime(DateTime.ParseExact("YouDateString", "MM/dd/yyyy", CultureInfo.InvariantCulture)); Try this DateTime dateTime = new DateTime(); dateTime = Convert.ToDateTime(DateTime.ParseExact("YouDa ...
-
如果你知道字符串是你发布的确切格式,这是一个简单的解决方案: s = s.replace(/\/(\d)\//, '/0$1/'); 当然,您可能需要检查d/m/yyyy ,或d/mm/yyyy 。 在这种情况下,另一种选择是: s = s.replace(/\b\d\b/g, '0$&'); 同样,假设日期是整个字符串,而不是部分字符串。 模式如下: \b\d\b - 一个整数字的数字(由非字母数字字符或字符串边缘包裹) /g - 全球替换,因为我们可能有两场比赛。 0$& - 为整场比赛添加零。 H ...
-
a)解析 d <- as.Date( "06.12.2012", "%d.%m.%Y") b)格式 strftime(d, "%m-%d-%Y") 要么 format(d, "%m-%d-%Y") 所以找到下面的代码。 date.seq <- as.Date("2007-10-01"):as.Date("2007-10-31") new.dates <- data.frame(date = as.Date(date.seq, origin = "1970-01-01")) new.dates1 ...
-
对不起,我对这个话题有点困惑。 在您的原始问题中,您需要“确定当前日期是否为MM / DD / YYYY与DD / MM / YYYY格式”,因为您将“获取当前日期然后再添加3天”。 在我的第一个回答中,我解决了之前请求的两个点(我认为正确)。 但是,您最终使用的代码似乎解决了一个完全不同的问题:将语言环境日期格式转换为特定的特定日期格式。 如果这是新请求,那么这是我的新解决方案: @echo off setlocal EnableDelayedExpansion rem Get the date for ...
-
当date绑定到GridView时,它已经是一个String而不再是DateTime 。 我建议你将列的DataFormatString设置为{0:d} ,它将根据页面UI显示日期。 When date is bound to GridView, it is already a String and no more a DateTime. I suggest you set the DataFormatString of the column to {0:d}, which will display the ...
-
我想出了这个小函数,它检查你使用格式DD(separator)MM(sameseparator)YYYY 用DD,MM和YYYY作为整数。 function valid_date($input_date) { if(!preg_match('/(?P
\d{2})(?P \D)(?P \d{2})\2(?P \d{4})/',$input_date, $aux_date)) return false; $aux = mktime(0,0,0,$aux_ ... -
无法将我的日期dd / mm / yyyy格式化为mm / dd / yyyy(Cannot get my date of dd/mm/yyyy to format into mm/dd/yyyy)[2022-08-06]
这里的问题是new Date() 。 它不知道提供的日期,'05 / 03/2012',是3月5日。它假定它是5月3日。这是另一种方法 。 The issue here is new Date(). It does not know the provided date, '05/03/2012', is March 5. It assumes it to be May 3. Here is another way to do it. -
Date值根本没有任何格式。 将日期格式化为字符串并将其分配回变量时,它会再次解析为Date值,并丢失格式。 要以格式化的字符串形式保留日期,您需要将其保留为字符串: Dim formatted As String = myDate.ToString("yyyy-MM-dd") A Date value doesn't have any format at all. When you format the date into a string and assign it back to the varia ...
-
看看这篇文章 - 它可能会帮助你... 如何在经典的asp中转换日期字符串 Take a look at this post - it might help you out... How to transform a date-string in classic asp
-
这是不可能的,因为日期内部存储为数字,DD / MM / YYYY或MM / DD / YYYY格式只是数据的显示格式。 但是,您可以通过SQL函数更改数据转换为字符串的方式... This is not possible, as the date is internally stored as a number, the DD/MM/YYYY or MM/DD/YYYY format is only the display format of the data. You can, however, cha ...