You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django用户多地址关联报错求助:makemigrations字段关联错误

Fixing the ManyToMany Through Field Error in Your Django Models

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 AddressType model has two foreign keys: profile (points to Profile) and address (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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 09:28:54