views:

75

answers:

1

Given the following models, I need to return a list of Links for each Place, grouped by Category.

class Place(models.Model):
    name = models.CharField(max_length=100)

class Category(models.Model):
    name = models.CharField(max_length=100)
    description = models.TextField()

class Link(models.Model):
    name = models.CharField(max_length=100)
    url = models.URLField()
    place = models.ManyToManyField('Place')
    categories = models.ManyToManyField('Category')
    description = models.TextField()
    featured = models.BooleanField()
    published = models.BooleanField()
    date_added = models.DateField(auto_now_add=True)

The result would look something like:

Some Place
Information about Some Place ... (not really important to question)

Banks
Bank of America
Commerce Bank
First National Bank

Financial Services
Bank of America
Edward Jones

Loans
Commerce Bank
First National Bank

As you can see, a Link should be listed in every Category in which it belongs.

I tried to loop through categories and concatenate the querysets, but with ManyToMany fields, it doesn't seem possible to do the sort necessary that can be passed into the template and grouped there.

+1  A: 

What is the problem? I tried this myself on the console, here is the traceback, that should help you.

 >>> ny = Place.objects.create(name='NewYork')
 >>> bank = Category.objects.create(name='bank',description='aaa')
 >>> bofa = Link.objects.create(name='BofA',url='http://google.com',description='a')
 >>> bofa.place.add(ny)
 >>> bofa.categories.add(bank)
 >>> ny.link_set.all()
 [Link: Link object]    # This is `bofa`
 >>> ny.link_set.filter(categories=bank)
 [Link: Link object]
 >>> 

Where is the problem? To display all the links category wise, of a particular place,

  • Get the place object Use get_object_or_404. ny in the example above
  • Obtain all links in the place, filter for the category you need. (You may need to obtain list of all categories in this place, similarly.)
Lakshman Prasad
If you just do place.link_set.all() like that, links that are supposed to appear in multiple categories only show in the queryset once instead of once for each category in which they are listed. Not to mention there is no way to sort links by category name. I think the way to do this is to use an intermediary field for the ManyToMany relationships. That way the instances of each listing in each category can be retrieved and sorted.
Chris Miller