简体   繁体   中英

Django model foreign key from existing table

In my django project I use django-registration reusable app. I install this app and run syncdb. It's create for me table 'registration_registrationprofiles' in my database. Then I create a new app and write this code in my 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:

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. I suggest you locate the migration file it created (in your_app/migrations ) and check its 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).

Then manage.py makemigrations will detect the dependency and run migrations in the correct order.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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