manuel
manuel

Reputation: 847

Complex django query in a many to many relationship

I have the following models

class Book(models.Model):
    name        = models.CharField(max_length=140)

class UserProfile(models.Model):
    favorites    = models.ManyToManyField(Book, null=True, blank=True)
    user         = models.OneToOneField(User)

I need to craete a list of all books and show which ones are favorites and which ones are not.

I need a queryset for a view that gets me all the books like

Book.objects.all()

but i also need to know for each book if it is a favorite for that user and then pass this queryset to the template.

Thanks.

Upvotes: 3

Views: 363

Answers (1)

David Robinson
David Robinson

Reputation: 78600

This is a relatively straightforward use of the ManyToManyField.

class Book(models.Model):
    name        = models.CharField(max_length=140)

class UserProfile(models.Model):
    favorites    = models.ManyToManyField(Book, null=True, blank=True)
    user         = models.OneToOneField(User)

favorite_books = this_user_profile.favorites.all()
for b in Book.objects.all():
    if b in favorite_books:
        print "Book", b.name, "is a favorite of this user!"
    else:
        print "Book", b.name, "is not a favorite of this user!"

ETA: Since you say you want to add it to the template, give it to the template as a list of tuples.

book_list = [(b, (b in favorite_books)) for b in Book.objects.all()]

In your template, have the code

{% for book, is_favorite in book_list %}
    {% if is_favorite %}
        {% comment %} Do something with this favorite book {% endcomment %}
    {% else %}
        {% comment %} Do something with this non favorite book {% endcomment %}
    {% endif %}
{% endfor %}

Upvotes: 2

Related Questions