Search code examples
pythondjangomodelmany-to-many

'ManyToManyDescriptor' object is not iterable


i have this in views:

def watchlist(request):
    watchlist_list = User.watchlist
    context = {
        "watchlist_list": watchlist_list
    }

and this in models:

from django.contrib.auth.models import AbstractUser
from django.db import models

class all_auctions(models.Model):
    title = models.CharField(max_length= 14)
    description = models.TextField(blank=False)
    photo_url = models.CharField(max_length= 500)
class User(AbstractUser):
    watchlist = models.ManyToManyField(all_auctions, blank = True, related_name = "watchlist")
class bids(models.Model):
    bid = models.DecimalField(decimal_places = 2, max_digits = 100000)
class comments(models.Model):
    comment = models.TextField(blank=False)

and trying to do this in my watchlist.html (view all the auctions some1 has in their watchlist):

{% extends "auctions/layout.html" %}

{% block body %}
    <h2>Watchlisted Listings</h2>

    {% for watchlisted in watchlist_list %}
        <div>
        <div style = "width: 1400px; border: 1px solid grey;padding: 10px; margin: 10px; display:inline-block;" class = auction_class>
                <img src="{{watchlisted.photo_url}}" alt="no image">
                <div style = "display:inline-block;">
                    <h2>{{watchlisted.title}}</h2>
                    {{watchlisted.description}}
                </div>
            </div>
        </div>
    {% endfor %}
{% endblock %}

and as title suggests get error: 'ManyToManyDescriptor' object is not iterable. If i cant do it like this dont be mean and just say that i cant (because im sick of this people) but say how else to do this. And yes i did research.


Solution

  • .watch_list is a manager, not a QuerySet, and thus not iterable, you convert this into a QuerySet with .all() [Django-doc], you should also work with request.user, not User, since User is a class, not the user:

    def watchlist(request):
        watchlist_list = request.user.watchlist.all()
        context = {
            'watchlist_list': watchlist_list
        }
        # …

    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.