Hi guys,

I've got models like this:

        class Category(model.Model):
                pass

        class City(model.Model):
                pass

        class Listing(model.Model):
                city = model.ForeignKey(City)
                categories = model.ManyToMany(Category, related_name='listings')

and I have a template that iterates over all the categories and all the
listings for each category for a given city, e.g.,

        ALL LISTINGS IN CITY=NEW YORK
        Bars : Category
                ...
        Restaurants : Category
                Restaurant1 : Listing
                Restaurant2 : Listing

A simple view preparation of the data would be:

  city='new york'
  for category in Category.objects.all():
    for listing in category.listings.filter(city=city):
      # listing here

But I cannot do this in a template since templates don't allow
arguments to methods in the for loop, e.g., I cannot do

  {% for listing in category.listings.filter(city=city) %}


So, I can prepare the viewdata in a context object and pass that to the
template.  The most obvious choices all aren't very pretty:

  # alternative 1: put the objects into the context,
  # put the listings in the objects
  context['categories'] = Categories.objects.all()
  for category in context['categories']:
    category.city_listings = category.listings.filter(city=city)

  # alternative 2: put the objects into the context,
  # put the listings in a separate place
  context['categories'] = Categories.objects.all()
  for category in context['categories']:
    context[category.name + '_city_listings'] \
      = category.listings.filter(city=city)

  # alternative 3: create new structures for all data
  context['categories'] = []
  for category in Category.objects.all():
    c = category.__dict__.copy()
    c['listings'] = category.listings.filter(city=city)
    context['categories'].append(c)

These alternatives all have different problems:

[1] Dynamically adding an attribute to the objects doesn't seem nice;
is it?

[2] In the template, given the category object, how can I access the
city listings?

[3] Cumbersome, and isn't copying the object's dict like this a bit
dangerous and wasteful?


A final alternative is to create a templatetag for this, but this also
seems a bit cumbersome.


What is the recommended way in these cases?


Rgds,
Bjorn


--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users
-~----------~----~----~----~------~----~------~--~---

Reply via email to