与外键和ManyToMany关系的Django模型转换为相同的模型 [英] Django model with Foreign Key and ManyToMany relations to same model

查看:415
本文介绍了与外键和ManyToMany关系的Django模型转换为相同的模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个django模型,如下所示:

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

我试图向用户模型添加一个ManyToMany字段,如下所示:

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

我运行syncdb时出现这个错误:

  AssertionError:ManyToManyField(< django.db.models.fields.related.ForeignKey对象在0x19ddfd0>)是无效的。 ManyToManyField的第一个参数必须是一个模型,一个模型名称或字符串'self'

如果我把用户放入引号中,我得到了:

  sales.subscription:'User'与模型User有关系,要么没有安装,要么是抽象的。 

我知道用户模型已正确导入。任何想法为什么有2个字段指向用户模型会导致问题?在此先感谢...

解决方案

它失败的原因是因为您的字段名称与类名相同(用户)。使用小写字段名称,它是Django和Python中的标准约定。请参阅 Django编码风格



另外,您需要为您的关系添加 related_name 参数:

  class Subscription(models.Model):
user = models.ForeignKey(User)
sub_users = models.ManyToManyField(User,blank = True,null = True,related_name =订阅)


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

解决方案

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

这篇关于与外键和ManyToMany关系的Django模型转换为相同的模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆