我有一个使用SQLAlchemy填充对象的数据库,但我无法弄清楚如何在Django中创建模型。
我需要Show对象通过关系拥有Episode对象的数组。在数据库中,所有Episode对象都有一个' show_title'列和所有Show对象都有'剧集'
使用 SQLAlchemy ,
,对象看起来像这样 class AlphaShow(Base) :
__tablename__ = 'show'
title = Column(UnicodeText, primary_key = True)
description = Column(UnicodeText)
image = Column(UnicodeText)
episodes = relationship("Episode", backref="show")
def __init__(self,_meta) :
self.title = _meta.title
self.image = _meta.image
self.description = _meta.description
class Episode (Base) : #was without base
__tablename__= 'episode'
title = Column(UnicodeText, primary_key = True)
link = Column(UnicodeText)
show_title = Column(UnicodeText, ForeignKey('show.title'))
def __init__(self, _title, _link) :
self.title = _title
self.link = _link
我如何在 Django 中制作模型? 我试过了,但它没有用,
class Shows(models.Model) :
episodes = []
title = models.TextField(primary_key=True)
description = models.TextField()
image = models.TextField()
class Meta:
db_table = 'shows'
def __str__(self):
return self.title
class Episode(models.Model) :
title = models.TextField(primary_key=True)
link = models.TextField()
show_title = models.ForeignKey(Shows)
class Meta:
db_table = 'episodes'
def __str__(self):
return self.title
我想我错过的是什么是Django等同于SQLAlchemy'
episodes = relationship("Episode", backref="show")
非常感谢任何帮助!
答案 0 :(得分:5)
试试这个
class Shows(models.Model) :
title = models.TextField(primary_key=True)
description = models.TextField()
image = models.TextField()
class Meta:
db_table = 'shows'
def __str__(self):
return self.title
class Episode(models.Model) :
show = models.ForeignKey(Show, related_name="episodes")
title = models.TextField(primary_key=True)
link = models.TextField()
show_title = models.ForeignKey(Shows)
class Meta:
db_table = 'episodes'
def __str__(self):
return self.title