Django model with Foreign Key and ManyToMany relat

2020-07-13 09:21发布

问题:

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...

回答1:

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")