Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django model with Foreign Key and ManyToMany relations to same model

I have a django model as follows:

class Subscription(models.Model):
    Transaction = models.ManyToManyField(Transaction, blank=True, null=True)
    User = models.ForeignKey(User)
    ...etc...

I am trying to add a ManyToMany field to the User model as follows:

    SubUsers = models.ManyToManyField(User, blank=True, null=True)

but I get this error when I run syncdb:

AssertionError: ManyToManyField(<django.db.models.fields.related.ForeignKey object at 0x19ddfd0>) is invalid. First parameter to ManyToManyField must be either a model, a model name, or the string 'self'

If I encase User in quotes, I get instead:

sales.subscription: 'User' has a relation with model User, which has either not been installed or is abstract.

I know the User model is imported correctly. Any ideas why having 2 fields pointing to the User model causes problems? Thanks in advance...

like image 647
Gabriel Ross Avatar asked Sep 12 '11 16:09

Gabriel Ross


1 Answers

The reason why it fails is because the name of your field is the same as the class name (User). Use lowercase field names, it the standard convention in Django and Python. See Django Coding style

Also, you need to add a related_nameparameter to your relationship:

class Subscription(models.Model):
    user = models.ForeignKey(User)
    sub_users = models.ManyToManyField(User, blank=True, null=True, related_name="subscriptions")
like image 192
Filip Jukić Avatar answered Oct 24 '22 06:10

Filip Jukić