Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Many-to-many relationship with 'through' model returning error on migration

I'm trying to implement a system which allows for two Profile model objects to be a part of a Pair model object.

Here is the Profile, followed by a Pair model:

class Profile(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL,
                                on_delete=models.CASCADE,
                                null=True, blank=True)
    pair = models.ManyToManyField('self', through='Pair',
                                   symmetrical=False,
                                   related_name='pair_to+')

class Pair(models.Model):
    requester = models.ForeignKey(Profile, related_name='pairing_requester')
    accepter = models.ForeignKey(Profile, related_name='pairing_accepter')
    requester_learns = models.CharField(max_length=60, null=True)
    requester_teaches = models.CharField(max_length=60, null=True)  

The relationship between profiles should be symmetrical, such that (profile1, profile2) are a unique object and I should not expect a (profile2, profile1) to be created.

So, per this article, I am trying to create the relationship.

Upon makemigrations, I am receiving the error:

ERRORS:
<function ManyToManyField.contribute_to_class.<locals>.resolve_through_model at 0x1044b47b8>: (models.E022) <function ManyToManyField.contribute_to_class.<locals>.resolve_through_model at 0x1044b47b8> contains a lazy reference to user_profile.pair, but app 'user_profile' doesn't provide model 'pair'.
user_profile.Profile.pair: (fields.E331) Field specifies a many-to-many relation through model 'Pair', which has not been installed.

What am I doing wrong?

like image 363
Jay Jung Avatar asked Jan 18 '26 19:01

Jay Jung


1 Answers

class Pair(models.Model):
    requester = models.ForeignKey(Profile, related_name='pairing_requester')
    accepter = models.ForeignKey(Profile, related_name='pairing_accepter')
    requester_learns = models.CharField(max_length=60, null=True)
    requester_teaches = models.CharField(max_length=60, null=True)  

class Profile(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL,
                                on_delete=models.CASCADE,
                                null=True, blank=True)
    pair = models.ManyToManyField('self', through='Pair',
                                   symmetrical=False,
                                   related_name='pair_to+')

the thing that you are doing wrong is you need to mention the model before calling a relation to another model, django will create PAIR model first then will install model to the other model. so use this and before making migration drop the old migration files

like image 178
Exprator Avatar answered Jan 21 '26 09:01

Exprator