Django用户多地址关联报错求助:makemigrations字段关联错误
Hey there! Let's sort out this migration error you're hitting. The problem comes down to the order of fields in through_fields for your Profile.addresses ManyToMany relationship.
Why the Error Happens
Django requires through_fields to follow a specific order:(field_on_current_model, field_on_target_model)
In your code, you've got this order reversed. You wrote ('address', 'profile'), but let's break it down:
- The current model here is
Profile - The target model you're linking to is
Address - Your intermediate
AddressTypemodel has two foreign keys:profile(points to Profile) andaddress(points to Address)
You need to swap those two values in through_fields so Django can correctly map the relationships.
Corrected Code
Here's the fixed Profile class (only the addresses field is changed):
class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) nick_name = models.CharField('Nick name', max_length=30, blank=True, default='') bio = models.TextField(max_length=500, blank=True) image = models.ImageField(default='default.jpg', upload_to='profile_pics') addresses = models.ManyToManyField( Address, through='AddressType', # Corrected order: (field pointing to Profile, field pointing to Address) through_fields=('profile', 'address'), ) def __str__(self): return f'{self.user.username} Profile' def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path)
Your Address and AddressType models are perfectly fine as-is—only the through_fields order needed adjusting.
Let's Verify
After making this change, run python manage.py makemigrations again, and the error should disappear. Django will now correctly recognize how the intermediate model's foreign keys connect to the parent models.
内容的提问来源于stack exchange,提问作者user10011505

