Take the 2-minute tour ×
class Box(models.Model):
    owner = models.ForeignKey(User, related_name='user', verbose_name='Owner')
    name = models.CharField("Name", max_length=30)
    items = models.ManyToManyField('Item', through='BoxItem', blank=True, null=True)

class BoxItem(models.Model):
    item = models.ForeignKey('Item')
    box = models.ForeignKey('Box')
    quantity = models.IntegerField()

class Item(models.Model):
    name = models.CharField("Name Item", max_length=30)

In [1]: from project.app.models import *

In [2]: b = Box.objects.get(owner=1)

In [3]: b.items_all()

Out[4]: [<Item: PC>, <Item: Notebook>]
  1. How to convert this Output to list?
  2. How to add to this list quantity next to the name of Item? (Example: PC - 3, Notebook- 5)
share|improve this question
add comment

2 Answers

up vote 0 down vote accepted

What about something like:

 b = Box.objects.get(owner=1)

 [('%s - %s' % (box_item.item.name, box_item.quantity)) for box_item in b.items_all()]
share|improve this answer
add comment

In line 4 it appears that the result of b.items_all() is actually a QuerySet; you can use any of the QuerySet's methods; for most purposes (including list access) I usually use the QuerySet directly.

In order to have quantity shown next to the name of Item at Python shell level you can use the __unicode__ method at Model level; this should be easy to achieve if you have a one-to-one relationship between Item and BoxItem; recall that this would result in an additional join each time the __unicode__ function is called.

share|improve this answer
add comment

Your Answer


