在Django中使用无关联预制MySQL数据库并转换外键
Hey there! Let's walk through how to properly convert that IntegerField to a ForeignKey for your existing MySQL database in Django. Here's what you need to know and adjust:
Key Background
Your existing inquiry table has a company_id integer column that maps to the id of your Company table. Django's ForeignKey automatically uses a [field_name]_id column by default, so we can leverage that to avoid changing your database structure.
Correct Model Implementation
First, let's go with the Django-style recommended approach (following standard naming conventions):
class Inquiry(models.Model): id = models.AutoField(primary_key=True) # Explicitly set primary key to match your existing table company = models.ForeignKey('Company', on_delete=models.CASCADE, blank=True, null=True) class Meta: managed = False # Keep this as False since your table already exists in MySQL db_table = 'inquiry'
- We renamed the field to
company(instead ofcompany_id) – Django will automatically map this to the existingcompany_idcolumn in your database. blank=True, null=Truematches your originalIntegerFieldsettings, so existing empty values won't break things.managed=Falsetells Django not to modify the table structure (critical since you're working with a pre-existing database).
If You Need to Keep the Field Named company_id
If you want to retain the company_id field name in your model (not ideal for Django conventions, but doable), specify the db_column parameter to avoid Django adding an extra _id suffix:
class Inquiry(models.Model): id = models.AutoField(primary_key=True) company_id = models.ForeignKey('Company', on_delete=models.CASCADE, blank=True, null=True, db_column='company_id') class Meta: managed = False db_table = 'inquiry'
Important Notes
- Verify the
CompanyModel: Make sure yourCompanymodel is correctly configured with the rightdb_tablename that matches your MySQL table. - Using
managed=True(Optional): If you want Django to manage foreign key constraints in the database, you can setmanaged=True. But before running migrations:- Double-check that every
company_idvalue in theinquirytable exists in theCompanytable'sidcolumn (invalid values will cause migration failures). - Run
python manage.py makemigrationsfollowed bypython manage.py migrateto apply the foreign key constraint.
- Double-check that every
内容的提问来源于stack exchange,提问作者Abdul Haseeb

