[英]AttributeError: module 'django.db.models' has no attribute 'ManyToMany'
I am trying to make one of my model
objects a ManyToMany
Field, so I can access the objects through both models.我正在尝试使我的model
对象之一成为ManyToMany
字段,因此我可以通过这两个模型访问对象。
I am receiving the following error
.我收到以下error
。
listing = models.ManyToMany(Listings, blank=True, related_name="listing")
AttributeError: module 'django.db.models' has no attribute 'ManyToMany'
models.py
: models.py
:
class WatchList(models.Model):
listing = models.ManyToMany(Listings, blank=True, related_name="listing")
user = models.ForeignKey(User, on_delete=models.CASCADE, default="")
The name of the field is a ManyToManyField
[Django-doc] , so this includes the …Field
in ManyToMany Field
:该字段的名称是ManyToManyField
[Django-doc] ,因此这包括ManyToMany Field
中的…Field
Field :
from django.conf import settings
class WatchList(models.Model):
listing = models.ManyToManyField(Listings, blank=True, related_name='watchlists')
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
Note : It is normally better to make use of the
settings.AUTH_USER_MODEL
[Django-doc] to refer to the user model, than to use theUser
model [Django-doc] directly.注意:通常最好使用settings.AUTH_USER_MODEL
[Django-doc]来引用用户模型,而不是直接使用User
模型[Django-doc] 。 For more information you can see the referencing theUser
model section of the documentation .有关更多信息,您可以查看参考文档的User
模型部分。
Note : The
related_name=…
parameter [Django-doc] is the name of the relation in reverse , so from theListings
model to theWatchlist
model in this case.注意:related_name=…
参数[Django-doc]是反向关系的名称,因此在这种情况下从Listings
模型到Watchlist
模型。 Therefore it (often) makes not much sense to name it the same as the forward relation.因此,将其命名为与前向关系相同的名称(通常)没有多大意义。 You thus might want to consider renaming therelation tolisting
watchlists
.因此,您可能需要考虑将关系重命名为listing
watchlists
。
Note : normally a Django model is given a singular name, so
listing
instead of.注意:通常 Django 模型被赋予一个单数名称,因此使用listings
listing
而不是。listings
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.