Django模型,一对多的关系与反向引用[如何]

yxyvkwin  于 2023-08-08  发布在  Go
关注(0)|答案(1)|浏览(112)

我有一个数据库,我用SQLAlchemy填充了对象,但我不知道如何在Django中创建模型。
我需要显示对象通过关系有情节对象数组。在数据库中,所有Episode对象都有一个'show_title'列,所有Show对象都有'episodes'
使用 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")


任何帮助将非常感谢!

pdtvr36n

pdtvr36n1#

试试这个

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

字符串

相关问题