Django model with Foreign Key and ManyToMany relations to same model

偶尔善良 提交于 2019-12-06 03:17:22

问题


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


来源:https://stackoverflow.com/questions/7390901/django-model-with-foreign-key-and-manytomany-relations-to-same-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!