0

我有旧的 cms 数据库,结构不完美,无法修改,但我需要使用 django 进行查询

posts ( post_id)

posts_text ( post_id, post_text)

episode ( id, season_id, episode_name)

episode_post_relationship ( id, season_id, episode_id, post_id)

请帮助我创建具有正确表关系的 django 模型。我应该使用 OneToOneField、ForeignKey、ManyToManyField 等还是纯连接?

我正在尝试从episode_post_relationship表中获取情节。和。 但不能指定该表应该加入并且表相同。posts_textposts_textpostssome_other_colepisode_post_relationshipposts_textpost_idposts

4

1 回答 1

1

根据文档,您也可以连接到旧数据库。为此,您需要将当前的 Django 项目连接到该数据库,例如,通过 创建一个新项目django-admin.py startproject yourproject,然后转到设置并更新DATABASES设置,如下所示:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql', 
        'NAME': 'DB_NAME',
        'USER': 'DB_USER',
        'PASSWORD': 'DB_PASSWORD',
        'HOST': 'localhost',   # Or an IP Address that your DB is hosted on
        'PORT': '3306',
    }
}

然后运行python manage.py inspectdb。您也可以将其输出为模型,例如python manage.py inspectdb > models.py

更新:

据我所知,您的数据库应该是:

class Post(models.Model):
    post_id = models.AutoField(primary_key=True)

    class Meta:
        db_table = 'posts'

class PostText(models.Model):
    post = models.ForeignKey(Post)
    post_text = models.TextField()

    class Meta:
        db_table = 'posts_text'

class Season(models.Model):
    # season fields
    class Meta:
       db_table = 'season'

class Episode(models.Model):
    season = models.ForeignKey(Season)
    episode_name = models.CharField(max_length=255)  # depends on your DB
    posts = models.ManyToManyField(Post, through="EpisodePost")

    class Meta:
        db_table='episode'

class EpisodePost(models.Model):
    season = models.ForeignKey(Season)
    episode = models.ForeignKey(Episode)
    post = models.ForeignKey(Post)

    class Meta:
        db_table='episode_post_relationship'

但是,在您对上述关系进行任何操作之前,请确保备份您当前的数据库。

于 2018-11-23T20:48:18.060 回答