编写Python类时的约束

2024-04-23 09:35:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用python3.5.2和django1.11来使用SQLite

我面临这样一种情况:我想用某个名字给我的模型命名,但是用不同的名字我得到了不同的结果管理.py关于外键的迁移

shell示例:

你知道吗模块.py你知道吗

from django.db import models


class Place(models.Model):
    question_text = models.CharField(max_length=200)


class Choice(models.Model):
    question = models.ForeignKey(Place, on_delete=models.CASCADE)

跑Python3管理.pymakemigrations发布

Migrations for 'post':
  post/migrations/0001_initial.py   
    - Create model Choice
    - Create model Place
    - Add field question to choice'

将类选项重命名为示例“Rating”时:

from django.db import models


class Place(models.Model):
    question_text = models.CharField(max_length=200)


class Rating(models.Model):
    question = models.ForeignKey(Place, on_delete=models.CASCADE)

迁移尝试的输出:

Migrations for 'post':
  post/migrations/0001_initial.py
    - Create model Place
    - Create model Rating

您可能注意到外键实现消失了。我到处都查过了。尝试新项目。坚持了几天。是否有任何类命名限制或某种bug?你知道吗

祝你假期愉快,谢谢。你知道吗


Tags: frompy示例modelmodelscreateplace名字
1条回答
网友
1楼 · 发布于 2024-04-23 09:35:43

这不是一个bug,在这两种情况下都创建了外键。你知道吗

在第一种情况下,首先创建Choice模型,由于Place还不存在,因此在创建模型时它不能创建外键。因此,它将在创建Place模型之后的单独步骤中添加。你知道吗

在第二种情况下,首先创建Place模型,因此可以在CreateModel操作中为Rating创建外键。你知道吗

理想情况下,这两种情况都会尽可能地产生第二个输出,因为它包含的步骤较少,但这种优化尚未实现。你知道吗

相关问题 更多 >