Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

I am receiving the following error.

listing = models.ManyToMany(Listings, blank=True, related_name="listing")
AttributeError: module 'django.db.models' has no attribute 'ManyToMany'

models.py

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class WatchList(models.Model):
    listing = models.ManyToMany(Listings, blank=True, related_name="listing")
    user = models.ForeignKey(User, on_delete=models.CASCADE, default="")

>Solution :

The name of the field is a ManyToManyField [Django-doc], so this includes the …Field in ManyToManyField:

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 the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.


Note: The related_name=… parameter [Django-doc]
is the name of the relation in reverse, so from the Listings model to the Watchlist
model in this case. Therefore it (often) makes not much sense to name it the
same as the forward relation. You thus might want to consider renaming the listing relation to watchlists.


Note: normally a Django model is given a singular name, so Listing instead of Listings.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading