简体   繁体   English

现有表中的Django模型外键

[英]Django model foreign key from existing table

In my django project I use django-registration reusable app. 在我的django项目中,我使用django-registration可重用应用程序。 I install this app and run syncdb. 我安装此应用程序并运行syncdb。 It's create for me table 'registration_registrationprofiles' in my database. 它是在我的数据库中为我创建的表'registration_registrationprofiles'。 Then I create a new app and write this code in my models.py: 然后,我创建一个新的应用程序并将此代码写入我的models.py中:

class Comments(models.Model):
    text = models.TextField()
    pub_date = models.DateTimeField(auto_now=True)
    user = models.ForeignKey('registration_registrationprofiles')

And run manage.py makemigrations and it throw me exception: 并运行manage.py makemigrations,它会抛出异常:

ERRORS:
comments.Comments.user: (fields.E300) Field defines a relation 
with model 'registration_registrationprofiles', which is either
not installed, or is abstract.

How I can fix this problem? 我该如何解决这个问题?

Try this: 尝试这个:

from registration.models import RegistrationProfile

and then: 接着:

user = models.ForeignKey(RegistrationProfile)

Migrations can have dependencies declared. 迁移可以声明依赖项。 Usually, makemigrations does a good job with that, but it looks like it missed it this time. 通常,makemigrations在此方面做得很好,但这次似乎错过了。 I suggest you locate the migration file it created (in your_app/migrations ) and check its dependencies . 我建议您找到它创建的迁移文件(在your_app/migrations )并检查其dependencies It should look like this: 它看起来应该像这样:

class Migration(migrations.Migration):
    dependencies = [("registration", "0042_some_migration")]

    # operations...

The key here it the dependencies array should reference the registration app, and the latest migration (or at least the latest you depend on). dependencies数组中的键应引用注册应用程序以及最新的迁移(或至少是您依赖的最新版本)。

Then manage.py makemigrations will detect the dependency and run migrations in the correct order. 然后, manage.py makemigrations将检测依赖性并以正确的顺序运行迁移。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM